Create a .NET Core console app project with the following appsettings.json contents:
{
"Values": {
"key": "value"
}
}
Add NuGet references to:
Microsoft.Extensions.Configuration.Binder v2.1.1 Microsoft.Extensions.Configuration.Json v2.1.1Run the following:
class Program
{
static void Main()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var d = configuration.GetSection("Values").Get<Dictionary<string, string>>();
}
}
The result, d, is a dictionary with one pair, as expected.
However, replacing "key" with "k:ey" in the config and running again causes the following exception:
System.InvalidOperationException
HResult=0x80131509
Message=Cannot create instance of type 'System.String' because it is missing a public parameterless constructor.
Source=Microsoft.Extensions.Configuration.Binder
StackTrace:
at Microsoft.Extensions.Configuration.ConfigurationBinder.CreateInstance(Type type)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindDictionary(Object dictionary, Type dictionaryType, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.Get[T](IConfiguration configuration, Action`1 configureOptions)
...
I know : is a reserved character for IConfiguration paths, so maybe this isn't fixable, although is there not some way the : could be escaped when reading from JSON configuration sources?
I was following someone's example in https://stackoverflow.com/questions/42846296/how-to-load-appsetting-json-section-into-dictionary-in-net-core, and stumbled across this issue by accident (some of my Dictionary keys contain colons).
Any movement on this? I'd think mapping a dictionary would be a bit more flexible.
According to https://github.com/aspnet/Configuration/issues/792 this isn't supported and issue was closed.
Colons are reserved for special meaning in the keys, so they shouldn't be used as part of normal key values.
What the heck, it's distinctable key. Fix plz
Closing as @mguinness is correct here. The : is a reserved character (it denotes hierarchy), in fact User Secrets relies on that in it's JSON file.
For example, the following two pieces of JSON are considered equivalent in config (and that's by-design, required for User Secrets to work):
{
"Parent": {
"A": "1",
"B:" "2"
}
}
{
"Parent:A": "1",
"Parent:B": "2"
}
Most helpful comment
Any movement on this? I'd think mapping a dictionary would be a bit more flexible.