在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"));
}
}
上面是我的代码。结果是零。
如何获取数组?
在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>();
这为我工作,从我的配置返回一个字符串数组:
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" ]
}
}
这对我很管用;
创建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);
对于从配置返回复杂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 };
}
最近我还需要从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配置文件中的值读入一个字符串数组: