在 ASP.Net Core 中,可以使用 IOptions<T>
将配置值注入(inject)到类中.
所以如果我有以下 appsettings.json
配置:
{
"CustomSection": {
"Foo": "Bar"
},
"RootUrl": "http://localhost:12345/"
}
我可以注入(inject) IOptions<CustomSection>
进入我的构造函数(假设我已经定义了一个 CustomSection
类)并阅读 Foo
属性(property)。
如何注入(inject) RootUrl
设置到我的构造函数中还是不支持?
最佳答案
创建一个类如下
public class AppSettings {
public string RootUrl{ get; set; }
}
如下所示将其注入(inject)您的 startup.cs。
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
并在您的 Controller 中使用它,如下所示。
public CustomerController(IOptions<AppSettings> appSettings)
{
[variable] = appSettings.Value;
}
让我知道这是否适合您。
关于c# - ASP.Net Core 注入(inject)设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40478175/