Global Variables in ASP.Net Core 2

前端 未结 2 1016
闹比i
闹比i 2020-12-15 23:06

I am developing a web application in ASP.NET Core and currently have a large set of keys, such as stripe account keys. Instead of having them spread throughout the project i

2条回答
  •  长情又很酷
    2020-12-15 23:33

    In appsettings.json keep the variables.

    {
        "foo": "value1",
        "bar": "value2",
    }
    

    Create AppSettings class.

    public class AppSettings
    {
        public string foo { get; set; }
    
        public string bar { get; set; }
    }
    

    In Startup.cs file register.

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.Configure(Configuration);
    }
    

    Usage,

    public class MyController : Controller
    {
        private readonly IOptions _appSettings;
    
        public MyController(IOptions appSettings)
        {
            _appSettings = appSettings;
        }
        var fooValue = _appSettings.Value.foo;
        var barValue = _appSettings.Value.bar;
    }
    

提交回复
热议问题