0

I've already searched, there are similar questions, but with JSON Array in answers they are using IConfigure in the controller. I can use IConfigure only in Startup.

I have this JSON Array in appsettings.json

{
  "EmailList":{
    "EmailArray":[
      {
        "name":"John Algovich",
        "email":"John.Algovich@mail.com"
      },
      {
        "name":"Petr Algr",
        "email":"Petr.Algr@mail.com"
      },
      {
        "name":"Mathew Cena",
        "email":"Mathew.Cena@mail.com"
      }
    ]
  }
}

EmailList.cs:

public partial class EmailList 

{
  public List<string> EmailArray { get; set; }
  public string Name { get; set; }
  public string Email { get; set; }
}

There is a lot of injections in Startup.cs, so I used the same code for mine:

services.Configure<EmailList>(Configuration.GetSection("EmailList"));

Controller:

public class DevController : Controller
    {
        private readonly EmailList _devEmailList;
        private List<string> _emailList;

        public DevController(

            IOptions<EmailList> _devEmailList,
        {

            _devEmailList = devEmailList.Value; //This could be wrong since it's json array
            
_emailList = new List<string>();

        }
    }

Goal: How can I access email adresses in Controller and add it to the list?

I can't use IConfigure in Controller.

I was refering to this answer, but it originally having json without array. Questions with Json Arrays using IConfigure in Controller

vitalyag95
  • 39
  • 5
  • I think EmailList class does not represent the correct JSON from the appsettings.json file. – Chetan Oct 23 '20 at 04:41

1 Answers1

1

Your class definition doesn't mirror the structure of your json;

public class EmailAddress {
  public string Name { get; set; }
  public string Email { get; set; }
}

public class EmailList {
  public List<EmailAddress> EmailArray { get; set; }
}

Though you could simplify both;

public class EmailList:List<EmailAddress> {}
{
  "EmailList":[
    {
      "name":"John Algovich",
      "email":"John.Algovich@mail.com"
    },
    {
      "name":"Petr Algr",
      "email":"Petr.Algr@mail.com"
    },
    {
      "name":"Mathew Cena",
      "email":"Mathew.Cena@mail.com"
    }
  ]
}
Jeremy Lakeman
  • 9,515
  • 25
  • 29
  • Thank you! That helps, but the main goal access emails and add it to the list. Do you know how can I do that? – vitalyag95 Oct 23 '20 at 05:24