【问题标题】:Retrieve sections from config.json in ASP.NET 5在 ASP.NET 5 中从 config.json 中检索部分
【发布时间】:2015-11-02 22:52:46
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你做了什么类型的在线搜索..这是来自Dylan/JsonConfig GitHub的示例
  • @MethodMan 这是一个有趣的库,但我正在寻找可以与 ASP.NET 5 中内置的 IConfiguration 框架一起使用的东西。基本上我不太关心解析部分我从配置中脱离出来,因为我想知道如何首先检索它。
  • 示例:services.Configure<TypeHandlingCustomSection>(Configuration.GetConfigurationSection("CustomSection"));

标签: c# asp.net asp.net-core config.json


【解决方案1】:

我已经解决了一个类似的问题,我想将整个 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);

【讨论】:

    【解决方案2】:

    configuration.Get 用于获取值以获取您需要的部分

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

    【讨论】:

    • 我看到了这个方法,但是它返回了另一个IConfiguration对象;有没有办法从IConfiguration 枚举所有键/值对?我在weblog.west-wind.com/posts/2015/Jun/03/… 看到了强类型示例,但我正在寻找更动态的东西。
    • 我不知道枚举的方法,您可以使用 get 获取子键值,但您必须知道键,除非您将部分映射到据我所知的类型。
    【解决方案3】:

    我能够像这样使用未知键加载和绑定多个子部分(自您的帖子以来,语法略有变化;我建议密切关注 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】:

      编辑:为 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】:

        详细解释见 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】:

          您可以使用ConfigurationBinder 并将所有内容读取为Dictionary&lt;string, string&gt;

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-02-24
            • 1970-01-01
            • 2021-12-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多