appsettings.json
文件读取值。在我的
appsettings
中,我创建了两个部分,
SectionA
::
SectionB
i还创建了一个类,以映射此值与类属性:这是我的{
"SectionA": {
"SectionASubItem1": "test value",
"SectionASubItem2": "test value2"
},
"SectionB": {
"SectionBSubItem1": "test value",
"SectionBSubItem2": "test value2"
}
}
MyConfiguration
在public class MyConfiguration
{
public SectionA SectionA { get; set; }
public SectionB SectionB { get; set; }
}
public class SectionA
{
public string SectionASubItem1 { get; set; }
public string SectionASubItem2 { get; set; }
}
public class SectionB
{
public string SectionBSubItem1 { get; set; }
public string SectionBSubItem2 { get; set; }
}
类i创建了一个可变类型的program.cs
我存储JSON文件属性的变量类型:
IConfigurationRoot
绘制这样的部分:var myConfiguration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
问题是当我在控制器内部阅读
builder.Services.Configure<SectionA>(myConfiguration.GetSection("SectionA"));
builder.Services.Configure<SectionB>(myConfiguration.GetSection("SectionB"));
和sectionA
时,我会变得无效。因此,我没有从JSON文件中获得值。
sectionB
设置您的
appsetting.json
然后在"MyConfiguration": {
"SectionA": {
"SectionASubItem1": "test value AAAAAA",
"SectionASubItem2": "test value2 AAAA"
},
"SectionB": {
"SectionBSubItem1": "test value BBBBBB",
"SectionBSubItem2": "test value2 BBBBBB"
}
}
中以这样的配置:
Program.cs
最重要的一点是不要在构造函数中,您需要使用builder.Services.Configure<SectionB>(myConfiguration.GetSection("MyConfiguration"));
来设置值。
new MyConfiguration()
然后您可以在_configuration中获得值:
您可以做到这一点
在appsettings.json
dependency injection
private readonly IOptions<MyConfiguration> _configuration;
public WeatherForecastController(IOptions<MyConfiguration> configuration)
{
_configuration= configuration;
}
然后
"test": {
"MyConfiguration": {
"SectionA": {
"SectionASubItem1": "test value",
"SectionASubItem2": "test value2"
},
"SectionB": {
"SectionBSubItem1": "test value",
"SectionBSubItem2": "test value2"
}
}
}
最好使用ioptions,ioptionssnapshot或ioptionsMonitor.iOptionsMonitor与Ioptionssnapshot之间的差异
如果从课堂使用 您应该在控制器中进行ICONFIGURATION,然后传递到课堂 用于样品
builder.Services.Configure<MyConfiguration>(myConfiguration.GetSection("test:MyConfiguration"));