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

后端 未结 10 1481
误落风尘
误落风尘 2020-12-05 16:49

I am familiar w/ loading an appsettings.json section into a strongly typed object in .NET Core startup.cs. For example:

public class CustomSection 
{
   publ         


        
10条回答
  •  离开以前
    2020-12-05 17:32

    For others who want to convert it to a Dictionary,

    sample section inside appsettings.json

    "MailSettings": {
        "Server": "http://mail.mydomain.com"        
        "Port": "25",
        "From": "info@mydomain.com"
     }
    

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

    public static Dictionary 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.

提交回复
热议问题