从配置中检索部分.ASP. json.净5

本文关键字:json ASP 配置 检索部 | 更新日期: 2023-09-27 18:07:10

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

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

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

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

从配置中检索部分.ASP. json.净5

我已经解决了一个类似的问题,我想把整个iconfigationroot或iconfigationsection绑定到一个字典。下面是一个扩展类:

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)来保留完整的section键路径或剥离section路径,留下一个相对路径。

var data = config.GetSection("CustomSection").ToDictionary(false);

配置。Get是用来获取一个值来获取你需要的部分

IConfiguration mysection = configuration.GetConfigurationSection("SectionKey");

我能够加载和绑定多个子节与未知的键像这样(语法略有变化,因为你的帖子;我建议密切关注github项目和他们的单元测试,看看它目前是如何工作的):

var objectSections = Configuration.GetSection("CustomObjects").GetChildren();
var objects = objectSections.ToDictionary(x => x.Key, x =>
{
    var obj = new CustomObject();
    ConfigurationBinder.Bind(x, obj);
    return obj ;
});

编辑:更新Core 1.0版本的答案。

如果使用强类型对象,现在可以这样做,例如:

public class CustomSection 
{
   public int A {get;set;}
   public int B {get;set;}
}
//In Startup.cs
services.Configure<CustomSection>(Configuration.GetSection("CustomSection"));
//You can then inject an IOptions instance
public HomeController(IOptions<CustomSection> options) 
{
    var settings = options.Value;
}

详细说明请参见https://dotnetcodr.com/2017/01/20/introduction-to-asp-net-core-part-3-the-configuration-file/

下面是一个来自网站的例子:

配置文件中有:

"Languages": {
  ".NET": [ "C#", "VB.NET", "F#" ],
  "JVM": ["Java", "Scala", "Clojure"]
}

按如下方式加载配置:

IConfigurationSection languagesSection = configRoot.GetSection("Languages");
IEnumerable<IConfigurationSection> languagesSectionMembers = languagesSection.GetChildren();
Dictionary<string, List<string>> platformLanguages = new Dictionary<string, List<string>>();
foreach (var platform in languagesSectionMembers)
{
    List<string> langs = (from p in platform.GetChildren() select p.Value).ToList();
    platformLanguages[platform.Key] = langs;
}

您可以使用ConfigurationBinder并将所有内容读取为Dictionary<string, string>

下面是一些可以用作示例的测试用例:https://github.com/aspnet/Configuration/blob/dev/test/Microsoft.Framework.Configuration.Binder.Test/ConfigurationCollectionBindingTests.cs