Configuration.GetValue<T>返回 null 但 Bind 有效 [英] Configuration.GetValue<T> returning null but Bind works
问题描述
我在从 appsettings.json
获取数据时遇到问题.该文件看起来像:
I'm having a problem getting data from my appsettings.json
.
The file looks like:
"Integrations": {
"System01": {
"Host": "failover://(tcp://localhost:61616)?transport.timeout=2000",
"User": "admin",
"Password": "admin"
},
"System02": {
"Host": "failover://(tcp://localhost:61616)?transport.timeout=2000",
"User": "admin",
"Password": "admin"
},
}
我有以下 DTO:
public class IntegrationsConfigurationDto
{
public string Host { get; set; }
public string User { get; set; }
public string Password { get; set; }
}
当试图阅读它时:
var config = _configuration.GetValue<IntegrationsConfigurationDto>("Integrations:System01");
我得到 null
.但如果我这样做:
I get null
. But if I do:
var config = new IntegrationsConfigurationDto();
_config.Bind("Integrations:System01", config);
我在 config
变量中正确获取了值.
I get the values correctly in my config
variable.
为什么会这样?在这种情况下如何使用 GetValue
?
Why does that happen? How can I use GetValue<T>
in this scenario?
提前致谢.
推荐答案
GetValue
仅适用于简单的值,例如 string
, int
等 - 它不会遍历嵌套配置的层次结构.
GetValue
only works for simple values, such as string
, int
, etc - it doesn't traverse the hierarchy of nested configuration.
ConfigurationBinder.GetValue
从具有指定键的配置中提取值并将其转换为指定类型.如果未找到键,重载允许您提供默认值.
ConfigurationBinder.GetValue<T>
extracts a value from configuration with a specified key and converts it to the specified type. An overload permits you to provide a default value if the key isn't found.
不要使用 Bind
,而是使用以下内容来避免创建自己的 IntegrationsConfigurationDto
实例:
Instead of using Bind
, use the following to avoid having to create your own instance of IntegrationsConfigurationDto
:
var config = _configuration.GetSection("Integrations:System01")
.Get<IntegrationsConfigurationDto>();
ConfigurationBinder.Get
绑定并返回指定的类型.Get
比使用 Bind
更方便.
ConfigurationBinder.Get<T>
binds and returns the specified type.Get<T>
is more convenient than usingBind
.
这篇关于Configuration.GetValue<T>返回 null 但 Bind 有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!