在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"));
}
}
上面是我的代码。结果是零。
如何获取数组?
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;
这为我工作,从我的配置返回一个字符串数组:
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);
}
你可以像这样使用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));
}
}