从 appsettings c# 中读取 json 数组

Read json array from appsettings c#

我的 appsettings.json

中有数组
"steps": [
{
  "name": "IMPORT",
  "enabled": true
},
{
  "name": "IMPORT_XML",
  "enabled": true
},
{
  "name": "COMPARE",
  "enabled": true
},
{
  "test_name": "COMPARE_TABLE",
  "enabled": true
}]

在我的 class 中,我正在尝试使用 IConfigurationRoot _configurationRoot

检索它

我试过:

var procSteps = _configurationRoot.GetSection("steps");
foreach (IConfigurationSection section in procSteps.GetChildren())
{
    var key = section.GetValue<string>("test");
    var value = section.GetValue<string>("enabled");
}

和:

var procSteps = _configurationRoot.GetSection("ExecutionSteps")
            .GetChildren()
            .Select(x => x.Value)
            .ToArray();

但是 none 他们检索了我的值。有谁知道这是怎么回事以及访问此类数组值的正确方法是什么?

创建一个对象模型来保存值

public class ProcessStep {
    public string name { get; set; }
    public bool enabled { get; set; }
}

然后使用 Get<T>

从部分获取数组
ProcessStep[] procSteps = _configurationRoot
    .GetSection("steps")
    .Get<ProcessStep[]>();

ASP.NET Core 1.1 and higher can use Get<T>, which works with entire sections. Get<T> can be more convenient than using Bind

引用Configuration in ASP.NET Core: Bind to an object graph