C# Dictionary sectionDictionary=新字典(); 列表部分名称=新列表(部分); sectionNames.ForEach(section=> { List sectionValues=configuration.GetSection(section) .可计算的() .Where(p=>p.Value!=null) .ToList(); foreach(节值中的var子节) { sectionDictionary.Add(subSection.Key,subSection.Value); } }); 返回部分字典;

C# Dictionary sectionDictionary=新字典(); 列表部分名称=新列表(部分); sectionNames.ForEach(section=> { List sectionValues=configuration.GetSection(section) .可计算的() .Where(p=>p.Value!=null) .ToList(); foreach(节值中的var子节) { sectionDictionary.Add(subSection.Key,subSection.Value); } }); 返回部分字典;,c#,asp.net-core,asp.net-core-mvc,C#,Asp.net Core,Asp.net Core Mvc,DotNet Core 3.1: Json配置: "TestUsers": { "User": [ { "UserName": "TestUser", "Email": "Test@place.com", "Password": "P@ssw0rd!" }, {

DotNet Core 3.1:

Json配置:

"TestUsers": 
{
    "User": [
    {
      "UserName": "TestUser",
      "Email": "Test@place.com",
      "Password": "P@ssw0rd!"
    },
    {
      "UserName": "TestUser2",
      "Email": "Test2@place.com",
      "Password": "P@ssw0rd!"
    }]
}
然后创建一个User.cs类,该类具有与上面Json配置中的用户对象相对应的自动属性。然后,您可以参考Microsoft.Extensions.Configuration.Abstracts并执行以下操作:

List<User> myTestUsers = Config.GetSection("TestUsers").GetSection("User").Get<List<User>>();
List myTestUsers=Config.GetSection(“TestUsers”).GetSection(“User”).Get();


这比其他答案简单得多。这是目前为止最好的答案。在我的例子中,Aspnet core 2.1 web app包括这两个nuget软件包。所以这只是一个换行。ThanksIt还可以处理对象数组,例如
\u config.GetSection(“AppUser”).Get()
我想知道为什么他们不能简单地使用
GetValue
键:
Configuration.GetValue(“MyArray”)
。如果你有一个像
“客户端”这样的对象数组:[{..},{..}]
,你应该调用
配置.GetSection(“客户端”).GetChildren()
。如果你有一个像
这样的文本数组“客户端”:[“”、“”、“”]
,您应该调用
.GetSection(“客户端”).GetChildren().ToArray().Select(c=>c.Value.ToArray()
。这个答案实际上会生成4项,第一项是节本身的空值。这是不正确的。我成功地这样调用它:
var Clients=Configuration.GetSection(”clientConfig=>newclient{ClientId=clientConfig[“ClientId”],ClientName=clientConfig[“ClientName”],…}.ToArray();
这些选项对我都不起作用,因为对象在“Clients”点返回null“以哈罗为例。我确信json格式良好,因为它与插入字符串[“item:0:childItem”]中的偏移量(格式为“item”):[{…},{…}]我收到一个错误,它需要在“MySettings”和“MyArray”之间加一个逗号。感谢您提供的信息。我相信这最能回答最初的问题。如果它不是简单的字符串数组,而是数组的数组呢?例如,这个报告定义数组,我想为每个报告检索
cols
数组:
“报告”:[{“名称”:“报告A”,“id”:“1”,“cols”:[{“顺序”:“1”,“名称”:“empid”},{“顺序”:“2”,“名称”:“firstname”}]},{“名称”:“报告B”,“id”:“2”},“cols”:[{“顺序”:“1”,“名称”:“typeID”},{“顺序”:“名称”:“描述”}]
为我工作。谢谢使用Microsoft.Extensions.Configuration.Binder也可以,但是如果一行代码就可以完成这项工作,我希望不要引用另一个Nuget软件包。这是令人惊讶的。您的答案非常完美。这看起来是正确的。但是选项模式(微软称之为)不需要选项类中的接口。你可以通过注入一个
IOptions
来获得你的选择,而不是增加一个单例的开销。正是我所寻找的,非常有魅力,谢谢!
public class HomeController : Controller
{
    private readonly IConfiguration _config;
    public HomeController(IConfiguration config)
    {
        this._config = config;
    }

    public IActionResult Index()
    {
        return Json(_config.GetSection("MyArray"));
    }
}
var item0 = _config.GetSection("MyArray:0");
IConfigurationSection myArraySection = _config.GetSection("MyArray");
var itemArray = myArraySection.AsEnumerable();
{
  "MySettings": {
    "MyArray": [
      "str1",
      "str2",
      "str3"
    ]
  }
}
public class MySettings
{
     public List<string> MyArray {get; set;}
}
services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));
public class HomeController : Controller
{
    private readonly List<string> _myArray;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _myArray = mySettings.Value.MyArray;
    }

    public IActionResult Index()
    {
        return Json(_myArray);
    }
}
public class HomeController : Controller
{
    private readonly MySettings _mySettings;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _mySettings = mySettings.Value;
    }

    public IActionResult Index()
    {
        return Json(_mySettings.MyArray);
    }
}
{
  "MySettings": {
    "MyValues": [
      { "Key": "Key1", "Value":  "Value1" },
      { "Key": "Key2", "Value":  "Value2" }
    ]
  }
}
var valuesSection = configuration.GetSection("MySettings:MyValues");
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
    var key = section.GetValue<string>("Key");
    var value = section.GetValue<string>("Value");
}
public void ConfigureServices(IServiceCollection services) {
    services.Configure<List<String>>(Configuration.GetSection("MyArray"));
    //...
}
using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.Configuration.Binder;
var myArray = _config.GetSection("MyArray").Get<string[]>();
"TestUsers": [
  {
    "UserName": "TestUser",
    "Email": "Test@place.com",
    "Password": "P@ssw0rd!"
  },
  {
    "UserName": "TestUser2",
    "Email": "Test2@place.com",
    "Password": "P@ssw0rd!"
  }
]
var testUsers = Configuration.GetSection("TestUsers")
   .GetChildren()
   .ToList()
    //Named tuple returns, new in C# 7
   .Select(x => 
         (
          x.GetValue<string>("UserName"), 
          x.GetValue<string>("Email"), 
          x.GetValue<string>("Password")
          )
    )
    .ToList<(string UserName, string Email, string Password)>();
"TestUsers": [
{
  "UserName": "TestUser",
  "Email": "Test@place.com",
  "Password": "P@ssw0rd!"
},
{
  "UserName": "TestUser2",
  "Email": "Test2@place.com",
  "Password": "P@ssw0rd!"
}],
public dynamic GetTestUsers()
{
    var testUsers = Configuration.GetSection("TestUsers")
                    .GetChildren()
                    .ToList()
                    .Select(x => new {
                        UserName = x.GetValue<string>("UserName"),
                        Email = x.GetValue<string>("Email"),
                        Password = x.GetValue<string>("Password")
                    });

    return new { Data = testUsers };
}
var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
    .Get<string[]>();
"AppSettings": {
    "CORS-Settings": {
        "Allow-Origins": [ "http://localhost:8000" ],
        "Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
    }
}
var myArray= configuration.GetSection("MyArray")
                        .AsEnumerable()
                        .Where(p => p.Value != null)
                        .Select(p => p.Value)
                        .ToArray();
string[] array = _config.GetSection("MyArray").Get<string[]>();
{
    "keyGroups": [
        {
            "Name": "group1",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature2And3",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature5Group",
            "keys": [
                "user5"
            ]
        }
    ]
}
public class KeyGroup
{
    public string name { get; set; }
    public List<String> keys { get; set; }
}
Microsoft.Extentions.Configuration.Binder 3.1.3
Microsoft.Extentions.Configuration 3.1.3
Microsoft.Extentions.Configuration.json 3.1.3
using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Collections.Generic;

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

configurationBuilder.AddJsonFile("keygroup.json", optional: true, reloadOnChange: true);

IConfigurationRoot config = configurationBuilder.Build();

var sectionKeyGroups = 
config.GetSection("keyGroups");
List<KeyGroup> keyGroups = 
sectionKeyGroups.Get<List<KeyGroup>>();

Dictionary<String, KeyGroup> dict = 
            keyGroups = keyGroups.ToDictionary(kg => kg.name, kg => kg);
public class MyArray : List<string> { }

services.Configure<ShipmentDetailsDisplayGidRoles>(Configuration.GetSection("MyArray"));

public SomeController(IOptions<MyArray> myArrayOptions)
{
    myArray = myArrayOptions.Value;
}
"MySetting": {
  "MyValues": [
    "C#",
    "ASP.NET",
    "SQL"
  ]
},
namespace AspNetCore.API.Models
{
    public class MySetting : IMySetting
    {
        public string[] MyValues { get; set; }
    }

    public interface IMySetting
    {
        string[] MyValues { get; set; }
    }
}
public void ConfigureServices(IServiceCollection services)
{
    ...
    services.Configure<MySetting>(Configuration.GetSection(nameof(MySetting)));
    services.AddSingleton<IMySetting>(sp => sp.GetRequiredService<IOptions<MySetting>>().Value);
    ...
}
public class DynamicController : ControllerBase
{
    private readonly IMySetting _mySetting;

    public DynamicController(IMySetting mySetting)
    {
        this._mySetting = mySetting;
    }
}
var myValues = this._mySetting.MyValues;
public static class IConfigurationRootExtensions
{
    public static string[] GetArray(this IConfigurationRoot configuration, string key)
    {
        var collection = new List<string>();
        var children = configuration.GetSection(key)?.GetChildren();
        if (children != null)
        {
            foreach (var child in children) collection.Add(child.Value);
        }
        return collection.ToArray();
    }
}
{
      "MyArray": [
          "str1",
          "str2",
          "str3"
      ]
}
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
string[] values = configuration.GetArray("MyArray");
        public static string[] Sections = { "LogDirectory", "Application", "Email" };
        Dictionary<string, string> sectionDictionary = new Dictionary<string, string>();

        List<string> sectionNames = new List<string>(Sections);
        
        sectionNames.ForEach(section =>
        {
            List<KeyValuePair<string, string>> sectionValues = configuration.GetSection(section)
                    .AsEnumerable()
                    .Where(p => p.Value != null)
                    .ToList();
            foreach (var subSection in sectionValues)
            {
                sectionDictionary.Add(subSection.Key, subSection.Value);
            }
        });
        return sectionDictionary;
"TestUsers": 
{
    "User": [
    {
      "UserName": "TestUser",
      "Email": "Test@place.com",
      "Password": "P@ssw0rd!"
    },
    {
      "UserName": "TestUser2",
      "Email": "Test2@place.com",
      "Password": "P@ssw0rd!"
    }]
}
List<User> myTestUsers = Config.GetSection("TestUsers").GetSection("User").Get<List<User>>();