在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中获取所有section的所有值
public static string[] Sections = { "LogDirectory", "Application", "Email" };
Dictionary<string, string> sectionDictionary = new Dictionary<string, string>();
List<string> sectionNames = new List<string>(Sections);
sectionNames.ForEach(section =>
{
List<KeyValuePair<string, string>> sectionValues = configuration.GetSection(section)
.AsEnumerable()
.Where(p => p.Value != null)
.ToList();
foreach (var subSection in sectionValues)
{
sectionDictionary.Add(subSection.Key, subSection.Value);
}
});
return sectionDictionary;
这为我工作,从我的配置返回一个字符串数组:
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" ]
}
}