ConfigurationBuilder Getsection() 在 .net core 2.1 控制台应用程序上返回 null。我已经搜索了很多博客和帖子,但有一个 json 示例,其中嵌套了 3-4 层。
Motive 是读取 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();
}
关于c# - asp.net core 2.1 ConfigurationBuilder GetSection 函数返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55798063/