how to get value from appsettings.json

前端 未结 6 722
时光说笑
时光说笑 2020-12-07 12:34
public class Bar
{
    public static readonly string Foo = ConfigurationManager.AppSettings[\"Foo\"];
}

In the .NET Framework 4.x, I can use the

6条回答
  •  难免孤独
    2020-12-07 12:40

    So there are really two ways to go about this.

    Option 1 : Options Class

    You have an appsettings.json file :

    {
      "myConfiguration": {
        "myProperty": true 
      }
    }
    

    You create a Configuration POCO like so :

    public class MyConfiguration
    {
        public bool MyProperty { get; set; }
    }
    

    In your startup.cs you have something in your ConfigureServices that registers the configuration :

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure(Configuration.GetSection("myConfiguration"));
    }
    

    Then in your controller/service you inject in the IOptions and it's useable.

    public class ValuesController : Controller
    {
        private readonly MyConfiguration _myConfiguration;
    
        public ValuesController(IOptions myConfiguration)
        {
            _myConfiguration = myConfiguration.Value;
        }
    }
    

    Personally I don't like using IOptions because I think it drags along some extra junk that I don't really want, but you can do cool things like hot swapping and stuff with it.

    Option 2 : Configuration POCO

    It's mostly the same but in your Configure Services method you instead bind to a singleton of your POCO.

    public void ConfigureServices(IServiceCollection services)
    {
        //services.Configure(Configuration.GetSection("myConfiguration"));
        services.AddSingleton(Configuration.GetSection("myConfiguration").Get());
    }
    

    And then you can just inject the POCO directly :

    public class ValuesController : Controller
    {
        private readonly MyConfiguration _myConfiguration;
    
        public ValuesController(MyConfiguration myConfiguration)
        {
            _myConfiguration = myConfiguration;
        }
    }
    

    A little simplistic because you should probably use an interface to make unit testing a bit easier but you get the idea.

    Mostly taken from here : http://dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/

提交回复
热议问题