c# - 配置 GetSection 返回对象部分的空值
问题描述
您好,我在 a 中使用 aajson
配置文件.NET Core App
,但我不明白为什么我会为作为对象的子部分获得 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
解决方案
你的例子没有错。Value
您所指的属性是 a string
,它null
适用于您的sect
和sect2
变量,仅仅是因为它们都不包含string
值 - 正如您所说,它们都是对象。
如果你想从 eg 中提取一个值sect2
,你可以使用这样的方法:
var aaValue = sect2.GetValue<int>("aa");
还有更多选项可以获取这样的部分的值。这是另一个绑定到 POCO 的示例:
public class TT
{
public int AA { get; set; }
public int X { get; set; }
}
var ttSection = sect2.Get<TT>();
如果您只想获得一个嵌套值,那么根本没有理由使用GetSection
。例如,您可以执行以下操作:
var redisHostname = configuration["Config:Dev:RedisAddress:Hostname"];
推荐阅读
- pandas - 将 pandas 多索引数据帧转换为一个简单的数据帧,所有索引都在列中
- python - Python to_datetime(来自 int/float 的 3 列)
- android - 使用 Flutter 录音
- unity3d - 统一铸造 3d
- python - 是否可以使用 Python 定义没有值的枚举?
- flutter - Flutter:将小部件移动到另一个位置
- ios - 当 imageview 在里面时,Swift CollectionView 会改变大小
- c - C语言中结构的动态内存分配
- javascript - 如何在Angular上动态显示选定行数据的总和?
- windows-10 - 在 Windows 10 上绑定一些全局热键失败