[英]asp.net core 2.1 ConfigurationBuilder GetSection function return null
ConfigurationBuilder Getsection()在.net core 2.1控制台應用程序上返回null。 我已經搜索了不少博客和帖子,但有json示例,其嵌套高達3-4級。
動機是閱讀json及其元素的整個“測試”鍵並進行操作。 我希望這個json可以在應用程序之外進行配置,因此可以在不對代碼進行任何更改的情況下對其進行更改。 下面是示例代碼
{
"test": {
"test1": {
"testing": {
"ApplicationName": "Microsoft Visual Studio",
"appid": "123456",
"ApplicationProfile": {
"Vs2015": "Microsoft Visual Studio 2015 Professional",
"VS_2017_Restricted": "Microsoft Visual Studio 2017 Enterprise (Restricted)"
}
}
},
"Applications": {
"app1": {
"Name": "application1",
"arrayOfSomething": [ "first array elment", "Secondarrayelement" ],
"anotherarraylikeabove": [],
},
"app2": {
"Name": "application2",
"Softwares": [ "first array elment", "second element" ],
"APACGroups": [],
"EMEA": [],
"OnlyForZurich": []
}
}
}
}
}
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
var test = configuration.GetSection("app2"); //test is null always
使用這個可能它的工作:
JSON:
"Locations": {
"Location": [ "Ford", "BMW", "Fiat" ]
},
啟動:
// Replace IConfiguration with IHostingEnvironment since we will build
// Our own configuration
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
// Set the new Configuration
Configuration = builder.Build();
}
並從以下數據獲取數據
public IActionResult Settings()
{
var array = Configuration.GetSection("Locations:Location")
.GetChildren()
.Select(configSection => configSection.Value);
return View();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.