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

Solution 1:

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);
});

Solution 2:

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.

Solution 3:

You can use Configuration.Bind(settings); in startup.cs class

And your settings class will be like

public class AppSettings
{
    public Dictionary<string, string> MobileConfigInfo
    {
        get;
        set;
    }
}

Hope it helps!

Solution 4:

I believe you can use the following code:

var config =  Configuration.GetSection("MobileConfigInfo").Get<Dictionary<string, string>>();