System.InvalidOperationException if configuration has dictionary with colon in key.
neyromant opened this issue · comments
Hi.
I got a error when I tried to read an object from the configuration that was loaded from the json file.
I wrote simple config file:
testdata.json:
{
"Urls": {
"https://site.com": "here are description for site.com",
"https://example.com": "here are description for example.com"
}
}
And I wrote simple program for read that config file:
Program.cs
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("testdata.json", true, true);
var config = builder.Build();
var initialData = config.Get<TestData>();
foreach (var urlData in initialData.Urls)
{
Console.WriteLine($"{urlData.Key} - {urlData.Value}");
}
}
}
public class TestData
{
public Dictionary<string, string> Urls { get; set; }
}
During the call to config.Get (), I get an error System.InvalidOperationException: 'Cannot create instance of type 'System.String' because it is missing a public parameterless constructor.'
It happens in https://github.com/aspnet/Configuration/blob/rel/2.0.0/src/Microsoft.Extensions.Configuration.Binder/ConfigurationBinder.cs#L366
because keys of my configuration's dictionary contains colon.
ConfigurationPath has propery KeyDelimiter = ":", ConfigurationBinder uses it to separate individual keys in a path and because of this, the ConfigurationBinder.BindDictionary method tries to create an instance of the string instead of the KeyValuePair instance.
My main question.
Is this behavior as designed and I can not use colons in the dictionary keys?
Or it is a bug and I can try to fix this bug in ConfigurationBinder?
@neyromant Colons are reserved for special meaning in the keys, so they shouldn't be used as part of normal key values.