gpt4 book ai didi

asp.net-core - 有没有办法在aspnetcore配置中的appsetting.json字典键中转义冒号?

转载 作者:行者123 更新时间:2023-12-04 16:00:03 25 4
gpt4 key购买 nike

我在 appsetting.json 中有这个提供者字典

  "AppSettings": {
"Providers": {
"http://localhost:5001": "Provider1",
"http://localhost:5002": "Provider2"
},
"ArrayWorks": [
"http://localhost:5001",
"http://localhost:5002"
],
"SoDoesColonInDictionaryValue": {
"Provider1": "http://localhost:5001",
"Provider2": "http://localhost:5002"
}
}

以下抛出异常,因为字典键中有冒号。
Configuration.GetSection("AppSettings").Get<AppSettings>()
但是,冒号作为字典值或数组工作正常,而不是字典键。
我读到冒号在配置中有特殊含义,但似乎没有办法逃脱。为什么?

编辑:
public class AppSettings
{
public string ApplicationName { get; set; }
public IDictionary<string, string> Providers { get; set; }
}

在调试 Configuration.GetSection("AppSettings") 时,你会得到这个
Key    AppSettings:Providers:http://localhost:5000
Value Provider1

它的目的是这样的
Key     AppSettings:Providers:http_//localhost_5000

但是似乎没有办法控制 Configuration 如何对待:::

最佳答案

编辑:
根据aspnet/Configuration#792

Colons are reserved for special meaning in the keys, so they shouldn'tbe used as part of normal key values.


  • 这不受支持,问题已关闭。
  • 还没有,直到现在还没有转义冒号字符,根据github上的Microsoft Asp.net存储库,但有一个开放的issue with #782在 github 存储库上将其移至 this backlog

  • 作为一种解决方法,您可以使用 appsetting:AppSettings 中的值反转 key ,并在如下代码中更正它:
    "AppSettings": {
    "Providers": {
    "Provider1":"http://localhost:5001",
    "Provider2":"http://localhost:5002"
    },
    "ArrayWorks": [
    "http://localhost:5001",
    "http://localhost:5002"
    ],
    "SoDoesColonInDictionaryValue": {
    "Provider1": "http://localhost:5001",
    "Provider2": "http://localhost:5002"
    }
    }
    并在代码中确保反转字典键和值如下
     var result = _configuration.GetSection("AppSettings:Providers")
    .GetChildren().ToDictionary(i=>i.Value,i=>i.Key);
    // result["http://localhost:5001"] return Provider1
    // result["http://localhost:5002"] return Provider2

    关于asp.net-core - 有没有办法在aspnetcore配置中的appsetting.json字典键中转义冒号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50788190/

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