在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"));
    }
}

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


如果你想要选择第一项的值,那么你应该这样做-

var item0 = _config.GetSection("MyArray:0");

如果你想选择整个数组的值,那么你应该这样做-

IConfigurationSection myArraySection = _config.GetSection("MyArray");
var itemArray = myArraySection.AsEnumerable();

理想情况下,您应该考虑使用官方文档建议的选项模式。这会给你带来更多的好处。


在应用程序设置中添加一个级别。json:

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

创建一个代表你的section的类:

public class MySettings
{
     public List<string> MyArray {get; set;}
}

在你的应用启动类中,绑定你的模型并将其注入到DI服务中:

services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));

在你的控制器中,从DI服务中获取配置数据:

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

ASP。NET Core的依赖注入服务就像一个魔法一样:)


如果你有一个像这样的复杂JSON对象数组:

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

您可以安装以下两个NuGet包:

using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.Configuration.Binder;

然后你将有可能使用以下扩展方法:

var myArray = _config.GetSection("MyArray").Get<string[]>();

这是一个老问题了,但是我可以给出一个用c# 7标准更新的。net Core 2.1的答案。假设我只在appsettings.Development.json中有一个列表,例如:

"TestUsers": [
  {
    "UserName": "TestUser",
    "Email": "Test@place.com",
    "Password": "P@ssw0rd!"
  },
  {
    "UserName": "TestUser2",
    "Email": "Test2@place.com",
    "Password": "P@ssw0rd!"
  }
]

我可以在Microsoft.Extensions.Configuration.IConfiguration被实现并像这样连接的任何地方提取它们:

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.First(), Visual Studio现在应该会显示“用户名”、“电子邮件”和“密码”选项。


对于从配置返回复杂JSON对象数组的情况,我调整了@djangojazz的答案,以使用匿名类型和动态而不是元组。

给定的设置部分:

"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();

它返回一个字符串数组:

{“str1”,“str2”,“str3”}


在ASP。NET Core 2.2及以后版本,我们可以在应用程序的任何地方注入IConfiguration 就像在你的例子中,你可以在HomeController中注入IConfiguration并像这样使用来获取数组。

string[] array = _config.GetSection("MyArray").Get<string[]>();

这对我很管用; 创建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;
}

appsettings.json:

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

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.Configure<MySetting>(Configuration.GetSection(nameof(MySetting)));
    services.AddSingleton<IMySetting>(sp => sp.GetRequiredService<IOptions<MySetting>>().Value);
    ...
}

Controller.cs

public class DynamicController : ControllerBase
{
    private readonly IMySetting _mySetting;

    public DynamicController(IMySetting mySetting)
    {
        this._mySetting = mySetting;
    }
}

访问值:

var myValues = this._mySetting.MyValues;

最近我还需要从appsettings中读取一个简单的字符串数组。Json文件(以及其他类似的. Json配置文件)。

对于我的方法,我创建了一个简单的扩展方法:

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

原始海报的.json文件如下所示:

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

使用上面的扩展方法,它使读取这个数组成为一个非常简单的一行事务,如下面的例子所示:

var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
string[] values = configuration.GetArray("MyArray");

在运行时,在值上设置一个'QuickWatch'的断点,以验证我们已经成功地将.json配置文件中的值读入一个字符串数组:


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

灯塔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文件:

{
    "AppSetting": {
        "ProfileDirectory": "C:/Users/",
        "Database": {
            "Port": 7002
        },
        "Backend": {
            "RunAsAdmin": true,
            "InstallAsService": true,
            "Urls": [
                "http://127.0.0.1:8000"
            ],
            "Port": 8000,
            "ServiceName": "xxxxx"
        }
    }
}

code

代码:

public static IConfigurationRoot GetConfigurationFromArgs(string[] args, string cfgDir)
{
    var builder = new ConfigurationBuilder()
            .SetBasePath(cfgDir)
            .AddCommandLine(args ?? new string[0]) // null  in UnitTest null will cause exception
            .AddJsonFile(Path.Combine(cfgDir, "setting.json"), optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
        // .AddInMemoryollection(configDictionary)
        ;
    var config = builder.Build();
    return config;
}

你可以使用services.AddOptions<AppSettingOption>("AppSetting")或者直接从iconfigationroot对象获取Object。

var cfg = GetConfigurationFromArgs(args, appDataDirectory);
cfg.GetSection("AppSetting").Get<AppSettingOption>()

输出:

{App.AppSettingOption}
    Backend: {App.BackendOption}
    Database: {App.DatabaseOption}
    ProfileDirectory: "C:/Users/"

你可以像这样使用Microsoft.Extensions.Configuration.Binder包:

在你的appsettings.json中

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

创建保存配置的对象:

 public class MyConfig
 {
     public List<string> MyArray { get; set; }
 }

在你的控制器绑定配置:

public class HomeController : Controller
{
    private readonly IConfiguration _config;
    private readonly MyConfig _myConfig = new MyConfig();

    public HomeController(IConfiguration config)
    {
        _config = config;
    }

    public IActionResult Index()
    {
        return Json(_config.Bind(_myConfig));
    }
}

在IOptions不起作用后,我发现这更简单,序列化时要做的事情也少得多。

//appsettings.json
"DatabaseModelCreationOptions": {
    "Users": [
      {
        "Id": "1",
        "UserName": "adminuser",
        "Email": "youremail@myemail.com",
        "Password": "!Ch4",
        "Player": "Admin",
        "PlayerInitials": "ADMIN",
        "ApiKey": "40753ey"
      }
    ],   
    "UserRoles": [
      {
        "Id": "af9986df",
        "Name": "Admin",
        "ConcurrencyStamp": "ddd53170"
      },
      {
        "Id": "03b82b0e",
        "Name": "Manager",
        "ConcurrencyStamp": "65da3f89"
      }
    ]
}

我需要的类,我不需要给你们看嵌套的类属性,你们可以在上面看到。

public class DatabaseModelCreationOptions
{
    public IEnumerable<User>? Users { get; set; }
    public IEnumerable<UserRole>? UserRoles { get; set; }
}

然后调用GetSection("")。得到

var dbOptions = configuration.GetSection("DatabaseModelCreationOptions")
    .Get<DatabaseModelCreationOptions>();

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