gpt4 book ai didi

c# - 无法从 appsettings.json 的 IConfiguration 提供程序映射实例

转载 作者:行者123 更新时间:2023-12-04 07:33:30 25 4
gpt4 key购买 nike

在我的 appsettings.test.json 我有以下结构。

{
"ViewOptionsConfiguration": {
"Default": {
"GroupingOptions": [
{ "Key": "SortKey1", "Label": "SortVal1" },
{ "Key": "SortKey2", "Label": "SortVal2" }
]
}
}
}
然后,我可以使用以下语法读取它(获取正确的值)。
string path = "ViewOptionsConfiguration:Default:GroupingOptions";

string key0 = config.GetValue<string>(path + ":0:Key")
string lab0 = config.GetValue<string>(path + ":0:Label")
string key1 = config.GetValue<string>(path + ":1:Label")
string lab1 = config.GetValue<string>(path + ":1:Label")
现在,我介绍了一个类 ViewOption像这样,打算将配置映射到此类元素的数组。
public class ViewOption 
{
public string Key { get; set; }
public string Label { get; set; }
}
我期待以下内容会起作用。遗憾的是,映射值似乎是 null ,所以我猜映射无法识别值。
ViewOption option0 = config.GetValue<ViewOption>(path + ":0")
List<ViewOption> options = config.GetValue<List<ViewOption>>(path)
我在映射中缺少什么?
我的解决方法是做类似下面的事情。但是,它像鸭子一样丑陋,而且,我需要单独计算数组的元素数量,这甚至更丑陋和更笨拙。
ViewOption option0 = new ViewOption(
config.GetValue<string>(path + ":0:Key"),
config.GetValue<string>(path + ":0:Label"));

最佳答案

我认为你非常接近。我在 .Net 5 目标控制台应用程序中做了类似下面的事情。我已经在这个 link 上发布了我对其他人的完整回答.

List<string> emailAddresses = _config.GetSection("EmailAddresses").Get<List<string>>();
foreach (string emailAddress in emailAddresses)
{

Console.WriteLine(emailAddress);
}
我的 appsettings.json 是:
{
"AppSettings": {

"FTPLocation": "\\\\FTPHostname\\\\c$\\\\Folder\\\\ftpSite\\\\Prod\\",
"FTPUri": "ftp://ftphostname/myFolder/",
"CSVFileName": "TestData.csv",
},
"ConnectionStrings": {
"AppDbConnString": "Server=sqlserverhost.domain.com;Database=DBName; Trusted_Connection=True; MultipleActiveResultSets=true"
,
"IdentityConnection": "Server=hostname.domain.com;Database=IdentityDBName; Trusted_Connection=True; MultipleActiveResultSets=true"
},
"EmailAddresses": [
"email1@test.com",
"email2@test.com",
"email3@test.com"
],
"Logging": {
"LogLevel": {
"Default": "Warning"
}
}
}

关于c# - 无法从 appsettings.json 的 IConfiguration 提供程序映射实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67842606/

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