configuration.GetValue列表返回null

问题描述 投票:4回答:3

我正在尝试使用GetValue<T>方法从appsettings.json文件中读取列表:

var builder = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

IConfigurationRoot configuration = builder.Build();
var rr = configuration.GetValue<IList<ConnectionSettings>>("Connections");


public class ConnectionSettings
{
    public string Name { get; set; }

    public string Host { get; set; }

    public string Account { get; set; }

    public string Password { get; set; }
}

和我的appsettings.json

{
"Connections": [
    {
      "Name": "",
      "Host": "192.168.1.5",
      "Account": "74687",
      "Password": "asdsdadsq"
    },
    {
      "Name": "",
      "Host": "127.0.0.1",
      "Account": "45654",
      "Password": "asdasads"
    }
  ]
}

问题是我总是得到null,我不明白为什么。

c# .net .net-core
3个回答
3
投票

我在github上发现了以下内容:GetValue not working with lists

长话短说:这是设计的。

所以你可以尝试这个:

var result = new List<ConnectionSettings>();
var rr = configuration.GetSection("Connections").Bind(result);

4
投票

根据the documentation for GetValue<>,它获取(单个)密钥的值并将其转换为指定的类型。不幸的是,如果无法转换该值,则不会抛出错误,这就是您遇到的情况。

我相信Get<>在你的情况下会更好。

var rr = configuration.GetSection("Connections").Get<IList<ConnectionSettings>>();

根据Get<>'s documentation,它:

尝试将配置实例绑定到类型T的新实例。如果此配置节具有值,则将使用该值。否则通过递归匹配属性名称与配置键进行绑定。

这允许您直接获取值,或者,如果找不到该属性,它将查找包含匹配属性的嵌套对象。

另一种选择是@AthanasiosKataras说;使用Bind<>。当您可能具有稀疏配置时,如果要使用默认值或计算值覆盖某些值,这将非常有用。


0
投票

当您使用非基本结构(如列表或数组)嵌套配置时,Configuration.Get是一个更好的选项。

{
  "Email": {
    "ToEmails": [
      "[email protected]",
      "[email protected]",
      "[email protected]"
    ]
}

List<string> emailTo = _config.GetSection("Email:ToEmails").Get<List<string>>()

foreach (string email in emailTo)
{
    sendGridMessage.AddTo(new EmailAddress(email));
}

或者使用Bind()

public static class ConfigurationRootExtentions
    {
        public static List<T> GetListValue<T>(this IConfigurationRoot configurationRoot, string section)
        {
            var result = new List<T>();
            configurationRoot.GetSection(section).Bind(result);
            return result;
        }
    }

参考文献[1]:https://blog.bitscry.com/2017/11/14/reading-lists-from-appsettings-json/参考文献[2]:https://github.com/aspnet/Configuration/issues/451

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