c# - 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>
解决方案
我相信正确的方法是使用ConfigurationBinder.Bind
(如此处所述)
var apiConfig = new ApiConfig();
configuration.GetSection("Authentication:ApiConfig").Bind(apiConfig);
编辑。看起来像
configuration.GetSection("Authentication").Bind("ApiConfig", apiConfig);
也应该工作。
推荐阅读
- javascript - react-select 2 设置值/标签
- ios - 从使用 MessageKit 创建的 ChatViewController 推送其他 ViewController
- python - Keras Tuner 抛出 InvalidArgumentError
- python - Python Setuptools:添加没有“main”功能的脚本作为“console_scripts”入口点的快速方法
- angular - 无法从 httpclient 获得响应,使用 get 方法
- python - 来自列名的 Seaborn 线条样式
- c++ - 从文件中查找单词并替换到其他文件中
- spring-boot - 升级到 Spring Boot 2.2.2 后,@DirtiesContext 无法正常工作
- python - 将 Spark DataFrame 转换为 Pandas DataFrame
- javascript - Mongoose - 按 id 数组查找,但检索有限的结果(每个 id 1 个)