Why does CreateDefaultBuilder not configure the host with appsettings.json values?
Part of the answer is to distinguish between host and app configuration. The documentation says that CreateDefaultBuilder
...
- Loads host configuration from:
- Environment variables prefixed with ASPNETCORE_ ...
- Command-line arguments.
- Loads app configuration from:
- appsettings.json.
- appsettings.{Environment}.json.
From within CreateDefaultBuilder
, the reason that appsettings.json
does not automatically affect the host, is that those settings are configuring the app, and the app config does not affect the host config. The documentation indicates that when it says:
IWebHostBuilder
configuration is added to the app's configuration, but the converse isn't true — ConfigureAppConfiguration
doesn't affect the IWebHostBuilder configuration.
Looking at the source code shows that the CreateDefaultBuilder
method only adds the appsettings.json
values from within its call to ConfigureAppConfiguration
. That is why those values are not automatically impacting the host.
How can we configure the host with values from a *.json file?
CreateDefaultBuilder
does not automatically configure the host with a *.json
file. We need to do that manually, and the documentation specifies how. In the example the file is named hostsettings.json
, and the example adds it explicitly like this:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hostsettings.json")
.Build();
return WebHost.CreateDefaultBuilder(args)
// this impacts *both* host and app config
.UseConfiguration(config)
.UseStartup<Startup>();
There is no magic in the name hostsettings.json
. In fact, we could combine our host settings and our app settings into one file named appsettings.json
. The way CreateDefaultBuilder
works encourages us to keep those settings somewhat separate.
What keys can we put in a *.json file to configure the host?
This is the list of keys that we can use to configure the host:
"applicationName"
"startupAssembly"
"hostingStartupAssemblies"
"hostingStartupExcludeAssemblies"
"detailedErrors"
"environment"
"webroot"
"captureStartupErrors"
"urls"
"contentRoot"
"preferHostingUrls"
"preventHostingStartup"
"suppressStatusMessages"
"shutdownTimeoutSeconds"
ConfigurationBuilder
after all (not that there's anything wrong with that). – Threap