【问题标题】:How to properly read nested configuration values from config.json in ASP.NET5?如何在 ASP.NET5 中正确读取 config.json 中的嵌套配置值?
【发布时间】:2015-05-20 02:29:57
【问题描述】:

我关注了一些examples for ASP.NET 5,但对如何正确读取“嵌套”配置值(如果这是正确的术语)感到困惑。

这是config.json的相关部分:

{
    "ApplicationName" : "OwNextApp",
    "AppSettings": {
        "SiteTitle": "OwNext"
    },
}

以及HomeController.cs的相关部分:

public IActionResult About()
{
    var appNestedNameFailed = _config.Get("AppSettings.SiteTitle");
    var appNestedNameSuccess = _config.Get("AppSettings:SiteTitle");
    var appName = _config.Get("ApplicationName");
    ViewBag.Message = string.Format(@"Your 
        APP NAME: {0};
        APP NESTED NAME FAILED: {1}; 
        APP NESTED NAME SUCCESS: {2}", 
            appName, appNestedNameFailed, appNestedNameSuccess);

    return View();
}

appNestedNameFailed 的值为空(我在研究之前的初步尝试)。而appNestedNameSuccess 是有价值的;在我进行研究并在Configuration 的测试中发现之后(显示了相关代码):

// Assert
Assert.Equal("IniValue1", config.Get("IniKey1"));
Assert.Equal("IniValue2", config.Get("IniKey2:IniKey3"));

有人可以解释为什么会这样吗?为什么使用: 而不是. 有意义?从我与 JSON 数据的交互来看,. 符号通常可以正常工作,例如How to access nested json data

另外,我发现了类似的SO question,但这并没有解释为什么选择:

【问题讨论】:

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


    【解决方案1】:

    这是我们在第一次创建配置模型时决定的约定。我们从 json 开始,: 是那里的分隔符。

    无论如何,如果您不想担心这些约定,我建议使用 ConfigurationBinder 将配置绑定到模型(强类型对象)。 Here are the tests on GitHub 可以作为例子。

    【讨论】:

    • 所以怀疑它只是自然分隔符。感谢您的确认:)
    • 谢谢大家。我喜欢强类型,所以我使用ConfigurationBinder
    • 仅供参考,链接已失效
    • 感谢@RSid。我修复了链接
    • 链接又死了:(
    【解决方案2】:
    using Microsoft.Extensions.Configuration;
    using System.IO;
    
    IConfigurationRoot configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();
    
    var connectionString = configuration.GetValue<string>("ConnectionStrings:DefaultConnection");
    
    // or
    
    var connectionString2= configuration.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;  
    

    appsettings.json:

    {
      "ConnectionStrings": {
        "DefaultConnection": "myconnection"
      },
    }
    

    【讨论】:

    • 我不确定“GetSection”是否应该在第一个代码部分底部的 connectionString2 中出现两次。
    • @PaulSchroeder 您可以根据需要多次堆叠 .GetSection("sectionName") - 路径保持不变,每个部分由 : 字符分隔。
    【解决方案3】:

    深入了解JsonConfigurationFileParser 源的内部,并指责其中的进入/退出方法:

    private void VisitJObject(JObject jObject)
    {
        foreach (var property in jObject.Properties())
        {
            EnterContext(property.Name);
            VisitProperty(property);
            ExitContext();
        }
    }
    
    private void EnterContext(string context)
    {
        _context.Push(context);
        _currentPath = string.Join(":", _context.Reverse());
    }
    
    private void ExitContext()
    {
        _context.Pop();
        _currentPath = string.Join(":", _context.Reverse());
    }
    

    似乎 ASP.NET 团队应该留下更多有启发性的签入 cmets :)。

    我的最佳猜测是 config.json 文件中可能存储了需要在其中包含 . 的数据,而 : 会不太常见。例如:

    "AppSettings": {
        "Site.Title": "Is .NET getting faster?"
    },
    

    这是一个不好的例子,但他们希望尽可能“安全”并使用超出规范的东西似乎是合理的。如果你想存储一个类型的全名,那也会稍微容易一些,而无需担心杂散期。

    "AppSettings": {
        "ImportantTypeName": "WebApp.CoolStuff.Helpers.AwesomeClass"
    },
    

    【讨论】:

    • 这似乎很合理,我也是这么想的。但是,我希望得到一些更有启发性的东西。感谢您对此进行调查。
    • 再看这个config.json,我认为他们选择:是因为它用于嵌套数据,例如"AppSettings": {。无论如何。
    • 通常使用: 将对象嵌套在json 中,因为它表示键/值对。结果,它可能最终成为最自然的分隔符。抱歉,我无法为您找到更正式的答案:)。
    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 2016-12-24
    • 2011-03-14
    • 1970-01-01
    • 2018-06-03
    • 2019-03-09
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多