Whoever
Whoever

Reputation: 1399

Is there a way to escape colon in appsetting.json dictionary key in aspnetcore configuration?

I have this provider dictionary in 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"
      }
   }

And the following throw exception because there's colon in the dictionary key.

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

However, colon works fine as dictionary value, or array, just not dictionary key. I read colon has special meaning in config, but there seems no way to escape. Why?

Edit:

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

When debugging Configuration.GetSection("AppSettings"), you get this

Key    AppSettings:Providers:http://localhost:5000
Value  Provider1

It was intended to be something like this

Key     AppSettings:Providers:http_//localhost_5000

But there seems no way to control how Configuration treat the :::

Upvotes: 12

Views: 4112

Answers (1)

Osama AbuSitta
Osama AbuSitta

Reputation: 4066

Edit: According to aspnet/Configuration#792

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

  • This isn't supported and issue was closed.

  • Not yet, Until now there is no escape colon character, Accourding to Microsoft Asp.net repository on github, but there is an open issue with #782 on the github repository which move it to this backlog

As a workaround you can reverse the key with the value in appsetting:AppSettings and correct it in code like the below:

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

And in code make sure to reverse dictionary key and value as the below

 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

Upvotes: 9

Related Questions