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":"[email protected]"
      },
      {
        "name":"Petr Algr",
        "email":"[email protected]"
      },
      {
        "name":"Mathew Cena",
        "email":"[email protected]"
      }
    ]
  }
}

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

1
  • I think EmailList class does not represent the correct JSON from the appsettings.json file. Commented Oct 23, 2020 at 4:41

1 Answer 1

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":"[email protected]"
    },
    {
      "name":"Petr Algr",
      "email":"[email protected]"
    },
    {
      "name":"Mathew Cena",
      "email":"[email protected]"
    }
  ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That helps, but the main goal access emails and add it to the list. Do you know how can I do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.