首页 > 解决方案 > IConfiguration:意外的 GetValue 行为

问题描述

GetValue<T>返回 null 而不是构建对象。同时,GetSection与预期相同的关键工作。

预期结果:GetValue不返回 null,而是创建ApiConfig类的新实例,填充IConfiguration对象中的信息。根据this other answer,它看起来是实现我想要做的事情的正确方法。

public static void Test(IConfiguration configuration)
{
    var key = "Authentication:ApiConfig";

    var children = configuration.GetSection(key).GetChildren().ToList();
    // SUCCEEDED: children.Count == 3 (Url, Username and Password)

    var config1 = configuration.GetValue<ApiConfig>(key);
    // FAILED: config1 == null

    var config2 = configuration.GetSection("Authentication").GetValue<ApiConfig>("ApiConfig");
    // FAILED: config2 == null
}

public class ApiConfig
{
    public string Url { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

项目信息:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  ...

</Project>

标签: c#asp.net-core

解决方案


我相信正确的方法是使用ConfigurationBinder.Bind(如此所述)

var apiConfig = new ApiConfig();
configuration.GetSection("Authentication:ApiConfig").Bind(apiConfig);

编辑。看起来像

configuration.GetSection("Authentication").Bind("ApiConfig", apiConfig);

也应该工作。


推荐阅读