c# - 访问 IOption 类中 appsettings.json 文件中存储的键值对

标签 c# json azure asp.net-core-mvc asp.net-core-2.0

我正在我的 appsettings.json 中存储一个键值对数组文件:

{
  "ApplicationSettings": {
    ...
    "CellularProviders": [
      {
        "Cingular": "cingularme.com"
      },
      {
        "Nextel": "vtext.com"
      },
      {
        "Sprint": "messaging.sprintpcs.com"
      },
      {
        "T-Mobile": "tmomail.net"
      },
      {
        "Verizon": "messaging.nextel.com"
      },
      {
        "Virgin Mobile": "vmobl.com"
      }
    ]
    ...
}

目前,我使用 List<Dictionary<string,string>>Startup.cs 中填充的 POCO 类中:

public class ApplicationSettings
{
    ...
    public List<Dictionary<string,string>> CellularProviders { get; set; }

}

这是表示键值对数组的推荐方式吗?

此外,我希望能够使用应用程序的“设置”部分在 Azure 中管理此设置:

enter image description here

在此上下文中表示键值对数组的正确方法是什么?

最佳答案

您无法放置JSON进入应用程序设置,因为它是一组简单的键值对。为了覆盖您的 appsettings.json 中的设置您需要表示完整路径,按 : 分段s,作为键(值保持不变):

例如,一个 key将是CellularProviders:Cingularvalue设置为cingularme.com .

CellularProviders:Cingular = cingularme.com
CellularProviders:Nextel = vtext.com
CellularProviders:Sprint = messaging.sprintpcs.com
CellularProviders:T-Mobile = tmomail.net
CellularProviders:Verizon = messaging.nextel.com
CellularProviders:VirginMobile = vmobl.com

至于将其转换为 List<Dictionary<string, string>> ,我不确定我是否理解您为什么使用“词典列表”而不是 Dictionary<string, string>

一个Dictionary<TKey, TValue>几乎是 List<T>KeyValuePair<TKey, TValue>对象(注意,这有点过于笼统)。您应该考虑使用它:

public Dictionary<string,string> CellularProviders { get; set; }

这将允许您轻松地在集合中查找值,如下所示:

var providerValue = CellularProviders["Cingular"];

关于c# - 访问 IOption 类中 appsettings.json 文件中存储的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48611316/

相关文章:

c# - Automapper - 如何从源子对象映射到目标

javascript - 如何从 JSONP 语句中选择变量

python - 是否有适用于 Azure Synapse 的 Python SDK?

java - 当 null 从未返回时,端点方法怎么可能返回 null?

php - 通过 PHP 连接到 MySQL 的 JSON Web 钩子(Hook)

git - 致命: git repository not found (but can go to URL) in Azure Devops?

c# - 如何将跟踪/异常数据从控制台 C# 应用程序获取到 Application Insights

c# - 如何使用 TestScheduler 完成超时行为?

c# - NET 5 在 Entity Framework Core 上添加迁移时出错

c# - 移动 MainWindow.xaml