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

后端 未结 10 1503
误落风尘
误落风尘 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:40

    In .NET Core 3.1 you can do something like the following...

    appsettings.json:

    {
      "myConfig": {
        "foo": "bar",
        "myMappings": {
          "key1": "value1",
          "key2": "value2"
        }
      }
    }
    

    A configuration model

    MyConfig.cs

    public class MyConfig
    {
        public string Foo { get; set; }
        public Dictionary MyMappings { get; set; }
    }
    

    Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure(configuration.GetSection("myConfig"));
    

    Class using the options:

    public class OptionsUsingClass
    {
        public OptionsUsingClass(IOptions myConfigOptions)
        {
            // Be wary of nulls in real code.
            var myConfig = myConfigOptions.Value;
    
            // Examples with the above data.
            myConfig.Foo.Should().Be("bar");
    
            myConfig.MyMappings["key1"].Should().Be("value1");
            myConfig.MyMappings["key2"].Should().Be("value2");
        }
    

    This was how I used appsettings.json dictionary mappings.

提交回复
热议问题