无论类型如何,GetValue<T> 总是得到 null/default

GetValue<T> always getting null/default regardless of type

我注意到以下语句产生了差异。

public static string GetValidation(this IConfiguration self, string key)
{
  IConfigurationSection section = self.GetSection(key);

  string value1 = section.Value;
  string value2 = section.GetValue<string>(key);

  return "";
}

配置中的相应部分已正确设置值并使用指定路径正确定位。

...
"SomePath": "Some value",
"AlsoTried": 13,
"AndEven": true,
...

第一个值符合预期,节点的内容。第二个为空。当我尝试输入整数和布尔值时,我得到了零和假,即默认值(当然我将配置文件中的值更改为非字符串,例如分别为 13 和 true。

我仔细检查了 the docs 并用谷歌搜索了这个问题,没有找到任何有用的信息。

我在这里遗漏了什么(因为我很确定这不是 .NET 中的错误,呵呵)?

您配置中的值应全部为字符串。使用 GetValue 将它们转换为正确的格式。配置应该是 的字典。

"SomePath": "Some value",
"AlsoTried": "13",
"AndEven": "true",

使用以下命令,您应该获得正确的值及其类型

section.GetValue<int>("AlsoTried"); // out type will int and value 13.
section.GetValue<bool>("AndEven"); // out type will be bool and value true

希望对您有所帮助。
发现这个 URL 也解释了配置和数据检索。 Good read.

我假设您将 test:SomeValue 作为密钥传递,并且您的配置如下所示:

"test": {
    "SomePath": "Some value",
    "AlsoTried": 13,
    "AndEven": true
}

您对 self.GetSection(key); 的调用是 return 您要求的特定值,例如

var section = self.GetSection("test:SomePath");

这意味着 section 现在是该路径的 "value",例如Some value,这就是为什么 section.Value 属性 return 是正确数据的原因。但是,当您调用 section.GetValue<string>("test:SomePath") 或仅调用 section.GetValue<string>("SomePath") 时,部分不包含 "SomePath" 的 KeyValuePair,因此您得到 null。

如果您在 self 上调用 GetValue<string>(key) 它将 return 正确的值:

var section = self.GetValue<string>(key);