gpt4 book ai didi

c# - 将 IConfigurationSection 绑定(bind)到没有 ASP.NET Core 的复杂对象

转载 作者:太空狗 更新时间:2023-10-29 20:47:16 27 4
gpt4 key购买 nike

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

应用设置.json:

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

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

最佳答案

Get<T>在包 Microsoft.Extensions.Configuration.Binder 中定义

关于c# - 将 IConfigurationSection 绑定(bind)到没有 ASP.NET Core 的复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45039136/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com