我有一些appsettings.json配置文件:
{
"PocoSettings": {
"ValueOne": "Foo",
"ValueTwo": "Bar"
}
}
以及应填充的设置对象:
public class PocoSettings
{
public string ValueOne;
public string ValueTwo;
}
我尝试在Startup.cs文件中填充它:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var MySettings = this.Configuration.GetSection("PocoSettings").Get<PocoSettings>();
// Inject MySettings into your DI container of choice here.
}
创建了MySettings
对象,但未填充值。 ValueOne
和ValueTwo
均为空。为什么呢?
答案 0 :(得分:5)
配置扩展需要显式公共getter和setter。如果它们是隐式的,或者get或set是私有的,则不会映射POCO对象。该课程应为:
public class PocoSettings
{
public string ValueOne { get; set; }
public string ValueTwo { get; set; }
}
答案 1 :(得分:0)
尝试一下:
PocoSettings MySettings = this.Configuration.Get<PocoSettings>();
我使用以下ConfigurationBuilder和我的SectionsCollection类对其进行测试。
var baseConfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("mySettings.json")
.Build();
SectionsCollection sectionsCollection = baseConfig.Get<SectionsCollection>();