【发布时间】:2018-12-20 16:01:56
【问题描述】:
您好,我在 .NET Core App 中使用了 json 配置文件,但我不明白为什么我的对象子节的值为 null:
{
"tt": {
"aa":3,
"x":4
},
"Url":333,
"Config": {
"Production": {
"RedisAddress": {
"Hostname": "redis0",
"Port": 6379
},
"OwnAddress": {
"Hostname": "0.0.0.0",
"Port": 9300
}
},
"Dev": {
"RedisAddress": {
"Hostname": "redis0",
"Port": 6379
},
"OwnAddress": {
"Hostname": "0.0.0.0",
"Port": 9300
},
"Logger": "logger.txt"
}
}
}
当我尝试GetSection("Config") 或GetSection("tt") 时,我得到了null 的值。但是它返回原始类型的值,例如我的情况Url。
有趣的是,如果我在configuration.Providers[0].Data 里面偷看,我会看到图片中的所有内容:
为什么 object 类型返回 null?
代码
WebHostBuilder builder = new WebHostBuilder();
builder.UseStartup<Startup>();
string appPath = AppDomain.CurrentDomain.BaseDirectory;
string jsonPath = Path.Combine(Directory.GetParent(Directory.GetParent(appPath).FullName).FullName, "appsettings.json");
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(appPath)
.AddJsonFile(jsonPath, optional: true, reloadOnChange: true)
.Build();
var sect = configuration.GetSection("Config");//has value null
var sect2 = configuration.GetSection("tt");//has value null
var sect3 = configuration.GetSection("Url"); has value 333
【问题讨论】:
-
这能回答你的问题吗? Configuration.GetSection always returns null
标签: c# asp.net-core