Configuration.GetSection()很容易获得原始字符串值,但不能获得复杂的值

时间:2018-06-15 18:09:40

标签: c# asp.net-core .net-core asp.net-core-2.0

这让我很惊讶。我正在使用Configuration.GetSection方法从appsettings.json读取值,简而言之,我的appsettings.json如下所示:

"AppSettings": 
  {  
    "PathPrefix": "",
    "Something": "Something else",
    "Clients":{"foo": "bar"}
  }

现在我惊讶的是,如果我做了类似下面的事情:

var foo = Configuration.GetSection("AppSettings:Clients:foo").Value;

然后它正确获取值。它获得值bar

但是,当我这样做时

 var clients = Configuration.GetSection("AppSettings:Clients").Value;

它返回null。它不仅是这个字段,每当我调用getSection方法获取任何复杂对象然后它返回null但是当我调用它来获取基本字符串值时它会正确获取值即使貌似,它在获取其父元素方面存在问题。这让我感到困惑,并提出了三个问题:

  1. 为什么在获取复杂值但没有获得基本字符串值时会出现问题?
  2. 是否按设计?如果是这样,为什么?
  3. 如果我想加载整个对象,我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以使用强类型对象加载整个对象。

首先,创建一个类(或类)来保存设置。根据您的示例,这将是:

public class AppSettings
{
    public string PathPrefix { get; set; }
    public string Something { get; set; }
    public Clients Clients { get; set; }
}

public class Clients
{
    public string foo { get; set; }
}

现在,您需要将Options服务添加到服务集合并从配置中加载设置:

public void ConfigureServices(IServiceCollection services)
{
    // This is only required for .NET Core 2.0
    services.AddOptions();

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

    services.AddMvc();
}

现在,您可以通过将属性注入到类中来访问这些属性,例如:

public class HomeController : Controller
{
    private readonly AppSettings _settings;

    public HomeController(IOptions<AppSettings> settings)
    {
        _settings = settings.Value;
    }
}

您还可以通过指定要加载的配置部分来加载ConfigureService方法中的子选项。

services.Configure<Clients>(Configuration.GetSection("AppSettings:Clients");

现在您可以注入IOptions<Clients>来访问这些设置

可以找到官方文档here

答案 1 :(得分:2)

您希望它返回什么?您可以使用Get<T>扩展方法获取复杂对象。试试这个:

var clients = Configuration.GetSection("AppSettings:Clients").Get<YourClientsType>();