在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"));
}
}
上面是我的代码。结果是零。
如何获取数组?
对于从配置返回复杂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" ]
}
}
这是一个老问题了,但是我可以给出一个用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现在应该会显示“用户名”、“电子邮件”和“密码”选项。
.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);
}