在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 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 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" ]
}
}
.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文件(以及其他类似的. 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配置文件中的值读入一个字符串数组: