gpt4 book ai didi

c# - 在 ASP.NET 5 中从 config.json 中检索部分

转载 作者:太空狗 更新时间:2023-10-30 00:40:00 25 4
gpt4 key购买 nike

假设我有一个像这样的 config.json:

{
"CustomSection": {
"A": 1,
"B": 2
}
}

我知道我可以使用 IConfiguration 对象来获取特定设置,即 configuration.Get("CustomSection:A"),但是我可以获取整个层次结构吗(任何类型——即使是原始字符串也可以)?当我尝试 configuration.Get("CustomSection") 时,我得到了一个 null 结果,所以我认为这在默认情况下不受支持。

我的用例是一次获取整个配置字典,而不必获取每个单独的设置 - 某些属性在编译时可能未知。

最佳答案

我已经解决了一个类似的问题,我想将整个 IConfigurationRoot 或 IConfigurationSection 绑定(bind)到一个字典。这是一个扩展类:

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);

关于c# - 在 ASP.NET 5 中从 config.json 中检索部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31929482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com