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

标签 c# asp.net-core .net-core appsettings

我有以下配置

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

我正在尝试将它绑定(bind)到以下对象

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; }
    }
}

问题是当我试图将文件绑定(bind)到字典时。他们不受约束。我得到一个值为 1 的键,并且值 FileOptions 都是用默认字符串值生成的。

这是我的配置映射。

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

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

最佳答案

They don't get bound. I get a key generated with the value of 1, and the value FileOptions are generated all with default string value.

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

  "Files": [
    {
      "Key": "asd",
      "Value": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      }
    }
  ]

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

"Options": {
  "Host": "123",
  "UserName": "test",
  "Password": "test",
  "Files": {
      "asd": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      },
      "someOtherKey" : {
        "HostLocation": "something",
        "RemoteLocation": "something"
      }
    }
  }
}

关于c# - 将 appsettings.json 映射到 Dictionary<string, Value>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58694791/

相关文章:

c# - 由契约(Contract)和 build 者设计

asp.net-core - HubContext的单元测试.net core 2.2 SignalR集线器问题

c# - 空数组 "Equals"的定义以及.NET和.NET core的区别

c# - 防止代码以随机顺序显示相同的图像?

c# - 检测像素是否在边界内的算法

asp.net - project.json 中的 'dependencies' 和 'frameworkAssemblies' 有什么区别?

c# - Entity Framework Core 使用 Unique 检查添加多行

visual-studio - 如何在 Visual Studio 2017 中为 .Net core 2.1 应用程序引用 F# 交互中的 Dll?

authentication - JWT token 认证,过期 token 仍然有效,.net 核心 Web Api

c# - 如何判断 JSON 结果是对象还是数组?