简体   繁体   English

如何从 ASP.NET5 中的 config.json 正确读取嵌套配置值?

[英]How to properly read nested configuration values from config.json in ASP.NET5?

I was following some examples for ASP.NET 5 and I got stumbled with how to properly read "nested" configuration values (if that is the proper term).我正在关注ASP.NET 5 的一些示例,并且偶然发现了如何正确读取“嵌套”配置值(如果这是正确的术语)。

Here is relevant portion of config.json :这是config.json相关部分:

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

And relevant portion of HomeController.cs :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();
}

Value for appNestedNameFailed is empty (my initial try before research). appNestedNameFailed值为空(我在研究前的初步尝试)。 And appNestedNameSuccess has value;appNestedNameSuccess是有价值的; after I did research and found in tests for Configuration (relevant code shown):在我做了研究并在配置测试中发现之后(显示了相关代码):

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

Can someone explain why is this the case?有人可以解释为什么会这样吗? Why would it make sense to use : over .为什么使用: over 有意义. ? ? From my interaction with JSON data usually .从我通常与 JSON 数据的交互来看. notation works fine, eg How to access nested json data .符号工作正常,例如如何访问嵌套的 json 数据

Also, I found similar SO question but this does not give explanation of why : was chosen.另外,我发现了类似的SO 问题,但这并没有解释为什么:被选中。

That's the convention that we decided upon when we first created the configuration model.这是我们第一次创建配置模型时决定的约定。 We started with json in mind and : is the delimiter there.我们从 json 开始,并且:是那里的分隔符。

Anyways, if you don't want to worry about those conventions, I recommend using the ConfigurationBinder which binds a configuration to a model (a strong type object).无论如何,如果您不想担心这些约定,我建议使用ConfigurationBinder ,它将配置绑定到模型(强类型对象)。 Here are the tests on GitHub that can serve as example. 以下是可以作为示例的GitHub 上的测试

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: appsettings.json:

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

Peering deep into the bowels of the JsonConfigurationFileParser source with blame on for the enter/exit methods that look at:深入研究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());
}

it seems that the ASP.NET team should leave more illuminating check-in comments :).似乎 ASP.NET 团队应该留下更多有启发性的签入评论:)。

My best guess is that there could be data stored in the config.json file that would need to have a .我最好的猜测是 config.json 文件中可能存储了需要. in it, whereas : would be less common.在其中,而:不太常见。 For instance:例如:

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

It's a bad example, but it seems reasonable that they wanted to be as "safe" as possible and use something outside of the norm.这是一个不好的例子,但他们希望尽可能“安全”并使用超出规范的东西似乎是合理的。 If you wanted to store a type's full name, that would also be slightly easier without needing to worry about a stray period.如果你想存储一个类型的全名,那也会稍微容易一些,而无需担心杂散期。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM