c# - asp.net core 2.1 ConfigurationBuilder GetSection函数返回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();
}
推荐阅读
- firebase - firestore云功能,删除聊天消息的方法
- php - 我如何修复 preg_match() 预期参数错误?
- flutter - 新创建的 SQFlite 数据库中的事务/批处理
- django - Django 2 在 forms.py 中手动保存 models.FileField
- javascript - 加载新页面而不刷新时CSS加载缓慢
- php - 将“starts-with”节点与“contains”值组合 PHP xpath 搜索
- reactjs - React / Redux:每当页面更改时都会自动调用操作
- java - KeyStoreException:此密钥库不支持探测,必须以指定类型加载
- python - 在 Python 中搜索 html 文件中的特定单词
- jquery - 带有对象变量的 JQuery concat 选择器