将IConfigurationSection绑定到没有aspnetcore的复杂对象

时间:2017-07-11 15:45:33

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

我有一个NetCore控制台应用程序,想要阅读appsettings.json并将一个部分解析为List<Param>(没有依赖注入或AspNetCore)。
我已经尝试了How do I bind a multi level configuration object using IConfiguration in a .net Core application?但似乎.Get<T>()已从netcoreapp1.1

中移除
IConfigurationSection myListConfigSection = configurationRoot.GetSection("ListA");

List<Param> paramList;

//Get does not exist
//paramList = myListConfigSection.Get<Param>();

string paramListJson = myListConfigSection.Value // is null
// won't work neither because paramListJson is null
paramList = JsonConvert.DeserializeObject<Param>(paramListJson);

appsettings.json:

{
  "ListA": [
    { "ID": "123", "Param": "ABC"},
    { "ID": "123", "Param": "JKS"},
    { "ID": "456", "Param": "DEF"}
  ]
}

是否有一种简单的方法可以将配置加载到对象中,还是我必须再次阅读配置文件并使用JsonConvert自行解析?

1 个答案:

答案 0 :(得分:21)

Get<T>在包Microsoft.Extensions.Configuration.Binder

中定义