查找IConfiguration中是否存在空值的Key。

问题描述 投票:1回答:1

我有。

IConfiguration cfg;
string key;

我必须检测是否有 key 内有 cfg 当键有 'null' 值。

我知道键在里面,我用调试器看到了,但是我需要一个方法来检测。

我想 cfg.GetSection(key).Exists() 会返回True。 但它总是返回 假的.

据文件显示: cfg.GetSection(key) 从来没有 即使key不存在,也会返回null,所以它没有任何帮助。

c# .net .net-core configuration core
1个回答
1
投票

使用 cfg.AsEnumerable() 来获取配置里面的密钥。你可以记录并查看它们。

foreach (var kv in cfg.AsEnumerable()) 
{
    Console.WriteLine("{0}: {1}", kv.Key, kv.Value);
}

=> 所以你需要做的就是找到你要找的特定键是否在这个IEnumerable中。

var keyNames = cfg.AsEnumerable().ToDictionary(x => x.Key, x => x.Value);

if (keyNames.ContainsKey(keyName))
{
    keyExistsInConfiguration = true;
}
© www.soinside.com 2019 - 2024. All rights reserved.