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

Who*_*ver 8 configuration appsettings asp.net-core

我在 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"
      }
   }
Run Code Online (Sandbox Code Playgroud)

下面抛出异常,因为字典键中有冒号。

Configuration.GetSection("AppSettings").Get<AppSettings>()

但是,冒号可以很好地用作字典值或数组,但不能用作字典键。我读到冒号在配置中具有特殊含义,但似乎没有办法逃脱。为什么?

编辑:

public class AppSettings
{
    public string ApplicationName { get; set; }
    public IDictionary<string, string> Providers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

调试 Configuration.GetSection("AppSettings") 时,您会得到这个

Key    AppSettings:Providers:http://localhost:5000
Value  Provider1
Run Code Online (Sandbox Code Playgroud)

本来是这样的

Key     AppSettings:Providers:http_//localhost_5000
Run Code Online (Sandbox Code Playgroud)

但似乎没有办法控制配置如何对待 :::

Osa*_*tta 7

编辑: 根据aspnet/Configuration#792

冒号在键中保留特殊含义,因此不应将它们用作普通键值的一部分。

  • 这不受支持,问题已关闭。

  • 还没有,到目前为止还没有转义冒号字符,根据 github 上的 Microsoft Asp.net 存储库,但是 github 存储库上有一个#782 的未决问题,将其移至此待办事项中

作为解决方法,您可以使用 appsetting:AppSettings 中的值反转密钥,并在代码中更正它,如下所示:

"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"
  }
}
Run Code Online (Sandbox Code Playgroud)

并在代码中确保反转字典键和值,如下所示

 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
Run Code Online (Sandbox Code Playgroud)