GetValue 总是获得null /默认值,与类型无关

问题描述 投票:0回答:2

我注意到以下陈述产生了差异。

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中的错误,呵呵)?

我注意到以下陈述产生了差异。公共静态字符串GetValidation(此IConfiguration self,字符串密钥){IConfigurationSection section = self.GetSection(key); ...

c# .net-core config appsettings
2个回答
0
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.