【问题标题】:Bind an IConfigurationSection to a complex object without ASP.NET Core在没有 ASP.NET Core 的情况下将 IConfigurationSection 绑定到复杂对象
【发布时间】:2017-12-15 18:53:21
【问题描述】:

我有一个 .NET Core 控制台应用程序,想要读取 appsettings.json 并将部分解析为 List<Param>(没有依赖注入或 ASP.NET Core)。
我已经尝试过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 解析它?

【问题讨论】:

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


【解决方案1】:

Get&lt;T&gt;在包Microsoft.Extensions.Configuration.Binder中定义

【讨论】:

  • 谢谢,它成功了。尽管我非常喜欢它,但有时我讨厌他们将所有内容都切换到不同的 nkpg。
  • #loveHate 是的,我一直在寻找并找到那个“额外”的 nkpg。
  • 这似乎与 GetSection 不同,因为它似乎将整个配置文件作为一个对象获取。
  • 您可以在 IConfiguratoinSection 上使用它并将此部分作为对象获取
猜你喜欢
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
  • 2019-11-11
  • 2015-01-29
  • 2011-08-31
  • 2021-10-06
相关资源
最近更新 更多