在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"));
}
}
上面是我的代码。结果是零。
如何获取数组?
.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);
}
灯塔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>>();