从 ASP.NET 5 中的 config.json 检索部分

Jos*_*ron 5 c# asp.net config.json asp.net-core

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

{
  "CustomSection": {
    "A": 1,
    "B": 2
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Jos*_*ron 1

编辑:更新 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;
}
Run Code Online (Sandbox Code Playgroud)