将 appsettings.json 映射到 Dictionary<string, Value>

5 c# appsettings .net-core asp.net-core

我有以下配置

"Options": {
  "Host": "123",
  "UserName": "test",
  "Password": "test",
  "Files": [
    {
      "Key": "asd",
      "Value": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我试图将它绑定到以下对象

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

这是我的配置映射。

_serviceCollection.Configure<SftpOptions>(_configuration.GetSection("Options"));
Run Code Online (Sandbox Code Playgroud)

出了什么问题以及如何将设置映射到选项类中。

Nko*_*osi 4

他们不受束缚。我得到一个生成的值为 1 的密钥,并且值 FileOptions 均使用默认字符串值生成。

这是正确的,因为Files显示的 JSON 中是一个数组

  "Files": [
    {
      "Key": "asd",
      "Value": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      }
    }
  ]
Run Code Online (Sandbox Code Playgroud)

JSON 需要如下所示才能满足所需的对象图

"Options": {
  "Host": "123",
  "UserName": "test",
  "Password": "test",
  "Files": {
      "asd": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      },
      "someOtherKey" : {
        "HostLocation": "something",
        "RemoteLocation": "something"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)