为什么我的appsettings.json文件中的配置值不通过Configuration.GetSection()映射到我的自定义POCO对象的字段。获取<myobject>?

时间:2016-12-29 23:57:40

标签: c# .net configuration .net-core

我有一些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对象,但未填充值。 ValueOneValueTwo均为空。为什么呢?

2 个答案:

答案 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>();