将appsettings.json映射到字典

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

我具有以下配置

"Options": {
  "Host": "123",
  "UserName": "test",
  "Password": "test",
  "Files": [
    {
      "Key": "asd",
      "Value": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      }
    }
  ]
}

并且我正在尝试将其绑定到以下对象

public class Options
{
    public string Host { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public Dictionary<string, FileOptions> Files { get; set; }

    public class FileOptions
    {
        public string HostLocation { get; set; }
        public string RemoteLocation { get; set; }
    }
}

问题是,当我尝试将文件绑定到字典时。他们不受束缚。我得到了一个值为1生成的密钥,并且值FileOptions都是使用默认字符串值生成的。

这是我的配置映射。

_serviceCollection.Configure<SftpOptions>(_configuration.GetSection("Options"));

出了什么问题,如何将设置映射到Options类。

c# asp.net-core .net-core appsettings
1个回答
0
投票

JSON必须看起来像以下内容,才能满足所需的对象图

"Options": {
  "Host": "123",
  "UserName": "test",
  "Password": "test",
  "Files": {
      "asd": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      },
      "someOtherKey" : {
        "HostLocation": "something",
        "RemoteLocation": "something"
      }
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.