Let's start by looking at how to configure your various configuration options.
Since ASP.NET Core 2.0, the configuration is hidden in the default configuration of WebHostBuilder
, and no longer part of Startup.cs
. This helps to keep the startup clean and simple.
In ASP.NET Core 3.1 and ASP.NET Core 5.0, the code looks like this:
// ASP.NET Core 3.0 and later
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}
}
Fortunately, you are also able to override the default settings to customize the configuration in a way you need it.
When you create a new ASP.NET Core project, you will already have appsettings.json
and appsettings.Development.json
configured. You can, and should, use these configuration files to configure your app; this is the pre-configured way, and most ASP.NET Core developers will look for an appsettings.json
file to configure the application. This is absolutely fine and works pretty well.
The following code snippet shows the encapsulated default configuration to read the appsettings.json
files:
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.ConfigureAppConfiguration((builderContext,
config) =>
{
var env = builderContext.HostingEnvironment;
config.SetBasePath(env.ContentRootPath);
config.AddJsonFile(
"appsettings.json",
optional: false,
reloadOnChange: true);
config.AddJsonFile(
$"appsettings.{env.EnvironmentName}.json",
optional: true,
reloadOnChange: true);
config.AddEnvironmentVariables();
})
.UseStartup<Startup>();
});
This configuration also sets the base path of the application and adds the configuration via environment variables. The ConfigureAppConfiguration
method accepts a lambda method that gets WebHostBuilderContext
and ConfigurationBuilder
passed in.
Whenever you customize the application configuration, you should add the configuration via environment variables as a final step, using the AddEnvironmentVariables()
method. The order of the configuration matters, and the configuration providers that you add later on will override the configurations added previously. Be sure that the environment variables always override the configurations that are set via a file. This way, you also ensure that the configuration of your application on an Azure App Service will be passed to the application as environment variables.
IConfigurationBuilder
has a lot of extension methods to add more configurations, such as XML or INI configuration files, and in-memory configurations. You can find additional configuration providers built by the community to read in YAML files, database values, and a lot more. In an upcoming section, we will see how to read INI files. First, we will look at using typed configurations.