假设我有一个config.json
像这样:
{
"CustomSection": {
"A": 1,
"B": 2
}
}
我知道我可以使用IConfiguration
对象获取特定设置,即configuration.Get("CustomSection:A")
,但是我可以获取整个层次结构(任何类型 - 即使是原始字符串也可以)?当我尝试时configuration.Get("CustomSection")
,我得到一个null
结果,所以我认为默认情况下不支持这一点。
我的用例是一次获取整个配置字典,而不必获取每个单独的设置 - 某些属性在编译时可能未知。
我已经解决了类似的问题,我想将整个 IConfigurationRoot 或 IConfigurationSection 绑定到字典。这是一个扩展类:
public class ConfigurationExtensions
{
public static Dictionary<string, string> ToDictionary(this IConfiguration config, bool stripSectionPath = true)
{
var data = new Dictionary<string, string>();
var section = stripSectionPath ? config as IConfigurationSection : null;
ConvertToDictionary(config, data, section);
return data;
}
static void ConvertToDictionary(IConfiguration config, Dictionary<string, string> data = null, IConfigurationSection top = null)
{
if (data == null) data = new Dictionary<string, string>();
var children = config.GetChildren();
foreach (var child in children)
{
if (child.Value == null)
{
ConvertToDictionary(config.GetSection(child.Key), data);
continue;
}
var key = top != null ? child.Path.Substring(top.Path.Length + 1) : child.Path;
data[key] = child.Value;
}
}
}
并使用扩展:
IConfigurationRoot config;
var data = config.ToDictionary();
var data = config.GetSection("CustomSection").ToDictionary();
有一个可选参数 (stripSectionPath) 可以保留完整的节键路径或剥离节路径,留下相对路径。
var data = config.GetSection("CustomSection").ToDictionary(false);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)