代码之家  ›  专栏  ›  技术社区  ›  Joshua Barron

从配置中检索节。json在ASP。净5

  •  5
  • Joshua Barron  · 技术社区  · 11 年前

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

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

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

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

    6 回复  |  直到 11 年前
        1
  •  4
  •   Michal Steyn    9 年前

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

    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);
    
        2
  •  2
  •   Joe Audette    11 年前

    配置Get用于获取值以获取所需的部分

    IConfiguration mysection = configuration.GetConfigurationSection("SectionKey");
    
        3
  •  1
  •   Adam Bruenderman    10 年前

    我能够像这样加载和绑定具有未知键的多个子部分(自您发表文章以来,语法略有变化;我建议关注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 ;
    });
    
        4
  •  1
  •   Joshua Barron    10 年前

    编辑:更新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;
    }
    
        5
  •  1
  •   lisa    8 年前

    有关详细说明,请参见 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;
    }
    
        6
  •  0
  •   Victor Hurdugaci    11 年前

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

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

    推荐文章