how to get value from appsettings.json

前端 未结 6 721
时光说笑
时光说笑 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:54

    Addition to answer from @MindingData. I like to map my settings recursively using Configuration.Bind(settings); so that I don't have to add every new section in ConfigureServices.

    Example:

    appsettings.json:

    {
        "MyConfiguration": {
            "MyProperty": true 
        }
    }
    

    Settings class, properties must match appsettings.json names:

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

    Startup.cs

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
    
            var settings = new Settings();
            Configuration.Bind(settings);
            services.AddSingleton(settings);
            ...
    

    Can be used in controllers like this:

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly Settings _settings;
    
        public ValuesController(Settings settings)
        {
            _settings = settings;
        }
    
        [HttpGet("GetValue")]
        public ActionResult Get()
        {
            return Ok(_settings.MyConfiguration.MyProperty);
        }
    }
    

提交回复
热议问题