从appsettings c#中读取json数组

use*_*222 2 .net c# json appsettings

我的数组中有 appsettings.json

"steps": [
{
  "name": "IMPORT",
  "enabled": true
},
{
  "name": "IMPORT_XML",
  "enabled": true
},
{
  "name": "COMPARE",
  "enabled": true
},
{
  "test_name": "COMPARE_TABLE",
  "enabled": true
}]
Run Code Online (Sandbox Code Playgroud)

在我的课堂上,我试图用 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");
}
Run Code Online (Sandbox Code Playgroud)

和:

var procSteps = _configurationRoot.GetSection("ExecutionSteps")
            .GetChildren()
            .Select(x => x.Value)
            .ToArray();
Run Code Online (Sandbox Code Playgroud)

但他们都没有找回我的价值观。有谁知道这是什么情况以及访问此类数组值的正确方法是什么?

Nko*_*osi 7

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

public class ProcessStep {
    public string name { get; set; }
    public bool enabled { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后使用该部分获取数组 Get<T>

ProcessStep[] procSteps = _configurationRoot
    .GetSection("steps")
    .Get<ProcessStep[]>();
Run Code Online (Sandbox Code Playgroud)

ASP.NET Core 1.1 及更高版本可以使用Get<T>,它适用于整个部分。Get<T>可以比使用更方便Bind

ASP.NET Core 中的参考配置:绑定到对象图