gpt4 book ai didi

c# - 将 appsettings.json 映射到 Dictionary

转载 作者:行者123 更新时间:2023-12-04 11:02:42 27 4
gpt4 key购买 nike

我有以下配置

"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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com