Reputation: 3856
Using .NET Core 2.0
Issue: If you use a json config file that contains a json object named "Urls", and have the Startup class constructor accept an IConfiguration parameter, then an error is thrown:
An item with the same key has already been added.
If you change the key name to be anything else, the error goes away. What's also strange is that you are allowed to have duplicate keys in your config files (they overwrite), but for some reason, "Urls" in particular causes this error.
public static class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddJsonFile("config.json", optional: false, reloadOnChange: true)
.Build();
BuildWebHost(args, config).Run();
}
public static IWebHost BuildWebHost(string[] args, IConfiguration config) =>
CreateBasicBuilder(args)
.UseConfiguration(config)
.UseStartup<Startup>()
.Build();
public static IWebHostBuilder CreateBasicBuilder(string[] args)
{
var builder = new WebHostBuilder();
if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
{
builder.UseContentRoot(Directory.GetCurrentDirectory());
}
builder.UseKestrel()
.UseIISIntegration()
.UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
});
return builder;
}
}
public class Startup
{
private readonly IHostingEnvironment _env;
private readonly IConfiguration _config;
public Startup(IConfiguration config, IHostingEnvironment env)
{
_env = env;
_config = config;
}
//other startup code below...
}
and here is config.json:
{
"Urls": {
"MyUrl": "https://test.com"
}
}
Upvotes: 0
Views: 1009
Reputation: 3856
As I suspected..."Urls" is used behind the scenes in Microsoft.AspNetCore.Hosting.Abstractions
So, you can use the "Urls" key, but the value must be a string. I had an object, so instead of trying to overwrite, it would try to add a new entry in its Dictionary and I'd get the error I was seeing.
So the fix for me is to not use "Urls" as a key.
Upvotes: 1