Configuration in .NET is possible with configuration providers. Several types of providers rely on various configuration sources. This article details all of the different configuration providers and their corresponding sources.
FileConfigurationProvider is the base class for loading configuration from the file system. The following configuration providers derive from FileConfigurationProvider:
Configures the JSON configuration provider to load the appsettings.json and appsettings.Environment.json files with the following options:
optional: true: The file is optional.
reloadOnChange: true: The file is reloaded when changes are saved.
Important
When adding configuration providers with IConfigurationBuilder.Add, the added configuration provider is added to the end of the end of the IConfigurationSource list. When keys are found by multiple providers, the last provider to read the key overrides previous providers.
An example appsettings.json file with various configuration settings follows:
From the IConfigurationBuilder instance, after configuration providers have been added, you can call IConfigurationBuilder.Build() to get the IConfigurationRoot object. The configuration root represents the root of a configuration hierarchy. Sections from the configuration can be bound to instances of .NET objects and later provided as IOptions<TOptions> through dependency injection.
Note
The Build Action and Copy to Output Directory properties of the JSON file must be set to Content and Copy if newer (or Copy always), respectively.
Consider the TransientFaultHandlingOptions class defined as follows:
The following code builds the configuration root, binds a section to the TransientFaultHandlingOptions class type, and prints the bound values to the console window:
In .NET 5 and earlier versions, add the name attribute to distinguish repeating elements that use the same element name. In .NET 6 and later versions, the XML configuration provider automatically indexes repeating elements. That means you don't have to specify the name attribute, except if you want the "0" index in the key and there's only one element. (If you're upgrading to .NET 6 or later, you may encounter a break resulting from this change in behavior. For more information, see Repeated XML elements include index.)
The application would write the following sample output:
C#
// Sample output:// section:section0:key:key0 = value 00// section:section0:key:key1 = value 01// section:section1:key:key0 = value 10// section:section1:key:key0 = value 11
Using the default configuration, the EnvironmentVariablesConfigurationProvider loads configuration from environment variable key-value pairs after reading appsettings.json, appsettings.Environment.json, and Secret manager. Therefore, key values read from the environment override values read from appsettings.json, appsettings.Environment.json, and Secret manager.
The : delimiter doesn't work with environment variable hierarchical keys on all platforms. For example, the : delimiter is not supported by Bash. The double underscore (__), which is supported on all platforms, automatically replaces any : delimiters in environment variables.
The following set commands set the environment keys and values of SecretKey and TransientFaultHandlingOptions.
.NET CLI
set SecretKey="Secret key from environment"
set TransientFaultHandlingOptions__Enabled="true"
set TransientFaultHandlingOptions__AutoRetryDelay="00:00:13"
These environment settings are only set in processes launched from the command window they were set in. They aren't read by web apps launched with Visual Studio.
With Visual Studio 2019 and later, you can specify environment variables using the Launch Profiles dialog.
The following setx commands can be used to set the environment keys and values on Windows. Unlike set, setx settings are persisted. /M sets the variable in the system environment. If the /M switch isn't used, a user environment variable is set.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Configuration.AddEnvironmentVariables(prefix: "CustomPrefix_");
using IHost host = builder.Build();
// Application code should start here.await host.RunAsync();
In the preceding code:
config.AddEnvironmentVariables(prefix: "CustomPrefix_") is added after the default configuration providers. For an example of ordering the configuration providers, see XML configuration provider.
Environment variables set with the CustomPrefix_ prefix override the default configuration providers. This includes environment variables without the prefix.
The prefix is stripped off when the configuration key-value pairs are read.
The default configuration loads environment variables and command-line arguments prefixed with DOTNET_. The DOTNET_ prefix is used by .NET for host and app configuration, but not for user configuration.
For more information on host and app configuration, see .NET Generic Host.
Connection string prefixes
The Configuration API has special processing rules for four connection string environment variables. These connection strings are involved in configuring Azure connection strings for the app environment. Environment variables with the prefixes shown in the table are loaded into the app with the default configuration or when no prefix is supplied to AddEnvironmentVariables.
When an environment variable is discovered and loaded into configuration with any of the four prefixes shown in the table:
The configuration key is created by removing the environment variable prefix and adding a configuration key section (ConnectionStrings).
A new configuration key-value pair is created that represents the database connection provider (except for CUSTOMCONNSTR_, which has no stated provider).
Microsoft recommends that you use the most secure authentication flow available. If you're connecting to Azure SQL, Managed Identities for Azure resources is the recommended authentication method.
Environment variables set in launchSettings.json
Environment variables set in launchSettings.json override those set in the system environment.
Azure App Service settings
On Azure App Service, select Add on the Settings > Environment variables page. Azure App Service application settings are:
Encrypted at rest and transmitted over an encrypted channel.
Exposed as environment variables.
Command-line configuration provider
Using the default configuration, the CommandLineConfigurationProvider loads configuration from command-line argument key-value pairs after the following configuration sources:
appsettings.json and appsettings.Environment.json files.
App secrets (Secret Manager) in the Development environment.
Environment variables.
By default, configuration values set on the command line override configuration values set with all the other configuration providers.
With Visual Studio 2019 and later, you can specify command-line arguments using the Launch Profiles dialog.
Command-line arguments
The following command sets keys and values using =:
.NET CLI
dotnetrun SecretKey="Secret key from command line"
The following command sets keys and values using /:
.NET CLI
dotnetrun /SecretKey "Secret key set from forward slash"
The following command sets keys and values using --:
.NET CLI
dotnetrun --SecretKey"Secret key set from double hyphen"
The key value:
Must follow =, or the key must have a prefix of -- or / when the value follows a space.
Isn't required if = is used. For example, SomeKey=.
Within the same command, don't mix command-line argument key-value pairs that use = with key-value pairs that use a space.
Key-per-file configuration provider
The KeyPerFileConfigurationProvider uses a directory's files as configuration key-value pairs. The key is the file name. The value is the file's contents. The Key-per-file configuration provider is used in Docker hosting scenarios.
To activate key-per-file configuration, call the AddKeyPerFile extension method on an instance of ConfigurationBuilder. The directoryPath to the files must be an absolute path.
Overloads permit specifying:
An Action<KeyPerFileConfigurationSource> delegate that configures the source.
Whether the directory is optional and the path to the directory.
The double-underscore (__) is used as a configuration key delimiter in file names. For example, the file name Logging__LogLevel__System produces the configuration key Logging:LogLevel:System.
Call ConfigureAppConfiguration when building the host to specify the app's configuration:
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
.NET
feedback
.NET
is an open source project. Select a link to provide feedback:
Learn the options pattern to represent groups of related settings in .NET apps. The options pattern uses classes to provide strongly-typed access to settings.