在 .net core 2.1 控制台应用程序中,ConfigurationBuilder Getsection() 返回 null。我已经搜索了很多博客和帖子,但是只有嵌套到3-4层的json示例。
目的是读取整个json中的“test”键以及它的元素并进行操作。我希望这个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
app2
is undertest/Applications/app2
. You will need to get the parent sections first.configuration.GetSection("test").GetSection("Applications").GetSection("app2")
- ESG