将 IConfigurationSection 绑定到没有 ASP.NET Core 的复杂对象 [英] Bind an IConfigurationSection to a complex object without ASP.NET Core

查看:30
本文介绍了将 IConfigurationSection 绑定到没有 ASP.NET Core 的复杂对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .NET Core 控制台应用程序,想要读取 appsettings.json 并将一个部分解析为 List(没有依赖注入或 ASP.NET核心).
我已经尝试过 如何我如何在 .net Core 应用程序中使用 IConfiguration 绑定多级配置对象? 但似乎 .Get() 已从 netcoreapp1.1 中删除代码>

I have a .NET Core console application and want to read the appsettings.json and parse a section as List<Param> (without Dependency Injection or ASP.NET Core).
I already tried How do I bind a multi level configuration object using IConfiguration in a .net Core application? but it seems like .Get<T>() got removed from 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:

appsettings.json:

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

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

Is there an easy way to load the config into the object or do I have to read the config file again and parse it myself with JsonConvert?

推荐答案

Get 定义在 Microsoft.Extensions.Configuration.Binder

这篇关于将 IConfigurationSection 绑定到没有 ASP.NET Core 的复杂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆