在appsettings.json

{
      "MyArray": [
          "str1",
          "str2",
          "str3"
      ]
}

在Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton<IConfiguration>(Configuration);
}

在HomeController

public class HomeController : Controller
{
    private readonly IConfiguration _config;
    public HomeController(IConfiguration config)
    {
        this._config = config;
    }
    
    public IActionResult Index()
    {
        return Json(_config.GetSection("MyArray"));
    }
}

上面是我的代码。结果是零。 如何获取数组?


当前回答

灯塔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配置中的User对象对应的auto属性。然后你可以引用Microsoft.Extensions.Configuration.Abstractions并执行以下操作:

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

其他回答

这对我很管用; 创建json文件:

{
    "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; }
}

nuget packages:

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;
}

.Net Core 7.x中处理对象的不同方法

在appsettings.json:

{
      "People": [
          { "FirstName": "Glen", "LastName": "Johnson", "Age": 30 },
          { "FirstName": "Matt", "LastName": "Smith", "Age": 40 },
          { "FirstName": "Fred", "LastName": "Williams", "Age": 50 }
      ]
}

Person类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

在代码中:

var appConfig = App.Current.AppConfiguration;   // Or could be passed in through DI
var children = appConfig.GetSection("People")
    .GetChildren()
    .ToList();

var people = new List<Person>();
foreach (var child in children)
{
    var rec = new Person
    {
        FirstName = appConfig[$"{child.Path}:FirstName"],
        LastName = appConfig[$"{child.Path}:LastName"],
        Age = int.Parse(appConfig[$"{child.Path}:Age"]),
    };
    people.Add(rec);
}

从appsettings.json中获取所有section的所有值

        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;

这为我工作,从我的配置返回一个字符串数组:

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" ]
    }
}