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