How to load appsetting.json section into Dictionary in .NET Core?

For others who want to convert it to a Dictionary,

sample section inside appsettings.json

"MailSettings": {
    "Server": "http://mail.mydomain.com"        
    "Port": "25",
    "From": "[email protected]"
 }

Following code should be put inside the Startup file > ConfigureServices method:

public static Dictionary<string, object> MailSettings { get; private set; }

public void ConfigureServices(IServiceCollection services)
{
    //ConfigureServices code......

    MailSettings = Configuration.GetSection("MailSettings").GetChildren()
                  .ToDictionary(x => x.Key, x => x.Value);
}

Now you can access the dictionary from anywhere like:

string mailServer = Startup.MailSettings["Server"];

One downside is that all values will be retrieved as strings, if you try any other type the value will be null.


Go with this structure format:

"MobileConfigInfo": {
    "Values": {
       "appointment-confirmed": "We've booked your appointment. See you soon!",
       "appointments-book": "New Appointment",
       "appointments-null": "We could not locate any upcoming appointments for you.",
       "availability-null": "Sorry, there are no available times on this date. Please try another."
 }
}

Make your setting class look like this:

public class CustomSection 
{
   public Dictionary<string, string> Values {get;set;}
}

then do this

services.Configure<CustomSection>((settings) =>
{
     Configuration.GetSection("MobileConfigInfo").Bind(settings);
});