91 KiB
title | author | description | monikerRange | ms.author | ms.custom | ms.date | no-loc | uid | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Configuration in ASP.NET Core | rick-anderson | Learn how to use the Configuration API to configure an ASP.NET Core app. | >= aspnetcore-3.1 | riande | mvc | 1/29/2021 |
|
fundamentals/configuration/index |
Configuration in ASP.NET Core
By Rick Anderson and Kirk Larkin
::: moniker range=">= aspnetcore-6.0"
Configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources:
- Settings files, such as appsettings.json
- Environment variables
- Azure Key Vault
- Azure App Configuration
- Command-line arguments
- Custom providers, installed or created
- Directory files
- In-memory .NET objects
This topic provides information on configuration in ASP.NET Core. For information on using configuration in console apps, see .NET Configuration.
View or download sample code (how to download)
Default configuration
ASP.NET Core web apps created with dotnet new or Visual Studio generate the following code:
var builder = WebApplication.CreateBuilder(args);
WebApplication.CreateBuilder initializes a new instance of the xref:Microsoft.AspNetCore.Builder.WebApplicationBuilder class with preconfigured defaults. The initialized WebApplicationBuilder
(builder
) provides default configuration for the app in the following order:
- ChainedConfigurationProvider : Adds an existing
IConfiguration
as a source. In the default configuration case, adds the host configuration and setting it as the first source for the app configuration. - appsettings.json using the JSON configuration provider.
- appsettings.
Environment
.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json. - App secrets when the app runs in the
Development
environment. - Environment variables using the Environment Variables configuration provider.
- Command-line arguments using the Command-line configuration provider.
Configuration providers that are added later override previous key settings. For example, if MyKey
is set in both appsettings.json and the environment, the environment value is used. Using the default configuration providers, the Command-line configuration provider overrides all other providers.
For more information on CreateBuilder
, see Default builder settings.
The following code displays the enabled configuration providers in the order they were added:
appsettings.json
Consider the following appsettings.json file:
The following code from the sample download displays several of the preceding configurations settings:
The default xref:Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider loads configuration in the following order:
- appsettings.json
- appsettings.
Environment
.json : For example, the appsettings.Production.json and appsettings.Development.json files. The environment version of the file is loaded based on the IHostingEnvironment.EnvironmentName. For more information, see xref:fundamentals/environments.
appsettings.Environment
.json values override keys in appsettings.json. For example, by default:
- In development, appsettings.Development.json configuration overwrites values found in appsettings.json.
- In production, appsettings.Production.json configuration overwrites values found in appsettings.json. For example, when deploying the app to Azure.
If a configuration value must be guaranteed, see GetValue. The preceding example only reads strings and doesn’t support a default value.
Using the default configuration, the appsettings.json and appsettings.Environment
.json files are enabled with reloadOnChange: true. Changes made to the appsettings.json and appsettings.Environment
.json file after the app starts are read by the JSON configuration provider.
Bind hierarchical configuration data using the options pattern
Using the default configuration, the appsettings.json and appsettings.Environment
.json files are enabled with reloadOnChange: true. Changes made to the appsettings.json and appsettings.Environment
.json file after the app starts are read by the JSON configuration provider.
See JSON configuration provider in this document for information on adding additional JSON configuration files.
Combining service collection
Security and user secrets
Configuration data guidelines:
- Never store passwords or other sensitive data in configuration provider code or in plain text configuration files. The Secret Manager tool can be used to store secrets in development.
- Don't use production secrets in development or test environments.
- Specify secrets outside of the project so that they can't be accidentally committed to a source code repository.
By default, the user secrets configuration source is registered after the JSON configuration sources. Therefore, user secrets keys take precedence over keys in appsettings.json and appsettings.Environment
.json.
For more information on storing passwords or other sensitive data:
- xref:fundamentals/environments
- xref:security/app-secrets: Includes advice on using environment variables to store sensitive data. The Secret Manager tool uses the File configuration provider to store user secrets in a JSON file on the local system.
Azure Key Vault safely stores app secrets for ASP.NET Core apps. For more information, see xref:security/key-vault-configuration.
Environment variables
Using the default configuration, the xref:Microsoft.Extensions.Configuration.EnvironmentVariables.EnvironmentVariablesConfigurationProvider loads configuration from environment variable key-value pairs after reading appsettings.json, appsettings.Environment
.json, and user secrets. Therefore, key values read from the environment override values read from appsettings.json, appsettings.Environment
.json, and user secrets.
The following set
commands:
- Set the environment keys and values of the preceding example on Windows.
- Test the settings when using the sample download. The
dotnet run
command must be run in the project directory.
set MyKey="My key from Environment"
set Position__Title=Environment_Editor
set Position__Name=Environment_Rick
dotnet run
The preceding environment settings:
- Are only set in processes launched from the command window they were set in.
- Won't be read by browsers launched with Visual Studio.
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.
setx MyKey "My key from setx Environment" /M
setx Position__Title Environment_Editor /M
setx Position__Name Environment_Rick /M
To test that the preceding commands override appsettings.json and appsettings.Environment
.json:
- With Visual Studio: Exit and restart Visual Studio.
- With the CLI: Start a new command window and enter
dotnet run
.
Call xref:Microsoft.Extensions.Configuration.EnvironmentVariablesExtensions.AddEnvironmentVariables* with a string to specify a prefix for environment variables:
In the preceding code:
config.AddEnvironmentVariables(prefix: "MyCustomPrefix_")
is added after the default configuration providers. For an example of ordering the configuration providers, see JSON configuration provider.- Environment variables set with the
MyCustomPrefix_
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 following commands test the custom prefix:
set MyCustomPrefix_MyKey="My key with MyCustomPrefix_ Environment"
set MyCustomPrefix_Position__Title=Editor_with_customPrefix
set MyCustomPrefix_Position__Name=Environment_Rick_cp
dotnet run
The default configuration loads environment variables and command line arguments prefixed with DOTNET_
and ASPNETCORE_
. The DOTNET_
and ASPNETCORE_
prefixes are used by ASP.NET Core for host and app configuration, but not for user configuration. For more information on host and app configuration, see .NET Generic Host.
On Azure App Service, select New application setting on the Settings > Configuration page. Azure App Service application settings are:
- Encrypted at rest and transmitted over an encrypted channel.
- Exposed as environment variables.
For more information, see Azure Apps: Override app configuration using the Azure Portal.
See Connection string prefixes for information on Azure database connection strings.
Naming of environment variables
Environment variable names reflect the structure of an appsettings.json file. Each element in the hierarchy is separated by a double underscore (preferable) or a colon. When the element structure includes an array, the array index should be treated as an additional element name in this path. Consider the following appsettings.json file and its equivalent values represented as environment variables.
appsettings.json
{
"SmtpServer": "smtp.example.com",
"Logging": [
{
"Name": "ToEmail",
"Level": "Critical",
"Args": {
"FromAddress": "MySystem@example.com",
"ToAddress": "SRE@example.com"
}
},
{
"Name": "ToConsole",
"Level": "Information"
}
]
}
environment variables
setx SmtpServer=smtp.example.com
setx Logging__0__Name=ToEmail
setx Logging__0__Level=Critical
setx Logging__0__Args__FromAddress=MySystem@example.com
setx Logging__0__Args__ToAddress=SRE@example.com
setx Logging__1__Name=ToConsole
setx Logging__1__Level=Information
Environment variables set in generated launchSettings.json
Environment variables set in launchSettings.json override those set in the system environment. For example, the ASP.NET Core web templates generate a launchSettings.json file that sets the endpoint configuration to:
"applicationUrl": "https://localhost:5001;http://localhost:5000"
Configuring the applicationUrl
sets the ASPNETCORE_URLS
environment variable and overrides values set in the environment.
Escape environment variables on Linux
On Linux, the value of URL environment variables must be escaped so systemd
can parse it. Use the linux tool systemd-escape
which yields http:--localhost:5001
groot@terminus:~$ systemd-escape http://localhost:5001
http:--localhost:5001
Display environment variables
The following code displays the environment variables and values on application startup, which can be helpful when debugging environment settings:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var config = app.Services.GetRequiredService<IConfiguration>();
foreach (var c in config.AsEnumerable())
{
Console.WriteLine(c.Key + " = " + c.Value);
}
Command-line
Using the default configuration, the xref:Microsoft.Extensions.Configuration.CommandLine.CommandLineConfigurationProvider loads configuration from command-line argument key-value pairs after the following configuration sources:
- appsettings.json and appsettings.
Environment
.json files. - App secrets 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.
Command-line arguments
The following command sets keys and values using =
:
dotnet run MyKey="My key from command line" Position:Title=Cmd Position:Name=Cmd_Rick
The following command sets keys and values using /
:
dotnet run /MyKey "Using /" /Position:Title=Cmd_ /Position:Name=Cmd_Rick
The following command sets keys and values using --
:
dotnet run --MyKey "Using --" --Position:Title=Cmd-- --Position:Name=Cmd--Rick
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,MySetting=
.
Within the same command, don't mix command-line argument key-value pairs that use =
with key-value pairs that use a space.
Switch mappings
Switch mappings allow key name replacement logic. Provide a dictionary of switch replacements to the xref:Microsoft.Extensions.Configuration.CommandLineConfigurationExtensions.AddCommandLine* method.
When the switch mappings dictionary is used, the dictionary is checked for a key that matches the key provided by a command-line argument. If the command-line key is found in the dictionary, the dictionary value is passed back to set the key-value pair into the app's configuration. A switch mapping is required for any command-line key prefixed with a single dash (-
).
Switch mappings dictionary key rules:
- Switches must start with
-
or--
. - The switch mappings dictionary must not contain duplicate keys.
To use a switch mappings dictionary, pass it into the call to AddCommandLine
:
Run the following command works to test key replacement:
dotnet run -k1 value1 -k2 value2 --alt3=value2 /alt4=value3 --alt5 value5 /alt6 value6
The following code shows the key values for the replaced keys:
For apps that use switch mappings, the call to CreateDefaultBuilder
shouldn't pass arguments. The CreateDefaultBuilder
method's AddCommandLine
call doesn't include mapped switches, and there's no way to pass the switch-mapping dictionary to CreateDefaultBuilder
. The solution isn't to pass the arguments to CreateDefaultBuilder
but instead to allow the ConfigurationBuilder
method's AddCommandLine
method to process both the arguments and the switch-mapping dictionary.
Set environment and command-line arguments with Visual Studio
Environment and command-line arguments can be set in Visual Studio from the launch profiles dialog:
- In Solution Explorer, right click the project and select Properties.
- Select the Debug > General tab and select Open debug launch profiles UI.
Hierarchical configuration data
The Configuration API reads hierarchical configuration data by flattening the hierarchical data with the use of a delimiter in the configuration keys.
The sample download contains the following appsettings.json file:
The following code from the sample download displays several of the configurations settings:
The preferred way to read hierarchical configuration data is using the options pattern. For more information, see Bind hierarchical configuration data in this document.
xref:Microsoft.Extensions.Configuration.ConfigurationSection.GetSection* and xref:Microsoft.Extensions.Configuration.IConfiguration.GetChildren* methods are available to isolate sections and children of a section in the configuration data. These methods are described later in GetSection, GetChildren, and Exists.
Configuration keys and values
Configuration keys:
- Are case-insensitive. For example,
ConnectionString
andconnectionstring
are treated as equivalent keys. - If a key and value is set in more than one configuration providers, the value from the last provider added is used. For more information, see Default configuration.
- Hierarchical keys
- Within the Configuration API, a colon separator (
:
) works on all platforms. - In environment variables, a colon separator may not work on all platforms. A double underscore,
__
, is supported by all platforms and is automatically converted into a colon:
. - In Azure Key Vault, hierarchical keys use
--
as a separator. The Azure Key Vault configuration provider automatically replaces--
with a:
when the secrets are loaded into the app's configuration.
- Within the Configuration API, a colon separator (
- The xref:Microsoft.Extensions.Configuration.ConfigurationBinder supports binding arrays to objects using array indices in configuration keys. Array binding is described in the Bind an array to a class section.
Configuration values:
- Are strings.
- Null values can't be stored in configuration or bound to objects.
Configuration providers
The following table shows the configuration providers available to ASP.NET Core apps.
Provider | Provides configuration from |
---|---|
Azure Key Vault configuration provider | Azure Key Vault |
Azure App configuration provider | Azure App Configuration |
Command-line configuration provider | Command-line parameters |
Custom configuration provider | Custom source |
Environment Variables configuration provider | Environment variables |
File configuration provider | INI, JSON, and XML files |
Key-per-file configuration provider | Directory files |
Memory configuration provider | In-memory collections |
User secrets | File in the user profile directory |
Configuration sources are read in the order that their configuration providers are specified. Order configuration providers in code to suit the priorities for the underlying configuration sources that the app requires.
A typical sequence of configuration providers is:
- appsettings.json
- appsettings.
Environment
.json - User secrets
- Environment variables using the Environment Variables configuration provider.
- Command-line arguments using the Command-line configuration provider.
A common practice is to add the Command-line configuration provider last in a series of providers to allow command-line arguments to override configuration set by the other providers.
The preceding sequence of providers is used in the default configuration.
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
.
Connection string prefix | Provider |
---|---|
CUSTOMCONNSTR_ |
Custom provider |
MYSQLCONNSTR_ |
MySQL |
SQLAZURECONNSTR_ |
Azure SQL Database |
SQLCONNSTR_ |
SQL Server |
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).
Environment variable key | Converted configuration key | Provider configuration entry |
---|---|---|
CUSTOMCONNSTR_{KEY} |
ConnectionStrings:{KEY} |
Configuration entry not created. |
MYSQLCONNSTR_{KEY} |
ConnectionStrings:{KEY} |
Key: ConnectionStrings:{KEY}_ProviderName :Value: MySql.Data.MySqlClient |
SQLAZURECONNSTR_{KEY} |
ConnectionStrings:{KEY} |
Key: ConnectionStrings:{KEY}_ProviderName :Value: System.Data.SqlClient |
SQLCONNSTR_{KEY} |
ConnectionStrings:{KEY} |
Key: ConnectionStrings:{KEY}_ProviderName :Value: System.Data.SqlClient |
File configuration provider
xref:Microsoft.Extensions.Configuration.FileConfigurationProvider is the base class for loading configuration from the file system. The following configuration providers derive from FileConfigurationProvider
:
INI configuration provider
The xref:Microsoft.Extensions.Configuration.Ini.IniConfigurationProvider loads configuration from INI file key-value pairs at runtime.
The following code clears all the configuration providers and adds several configuration providers: [!code-csharp]
In the preceding code, settings in the MyIniConfig.ini and MyIniConfig.Environment
.ini files are overridden by settings in the:
The sample download contains the following MyIniConfig.ini file:
The following code from the sample download displays several of the preceding configurations settings:
JSON configuration provider
The xref:Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider loads configuration from JSON file key-value pairs.
Overloads can specify:
- Whether the file is optional.
- Whether the configuration is reloaded if the file changes.
Consider the following code:
The preceding code:
- Configures the JSON configuration provider to load the MyConfig.json file with the following options:
optional: true
: The file is optional.reloadOnChange: true
: The file is reloaded when changes are saved.
- Reads the default configuration providers before the MyConfig.json file. Settings in the MyConfig.json file override setting in the default configuration providers, including the Environment variables configuration provider and the Command-line configuration provider.
You typically don't want a custom JSON file overriding values set in the Environment variables configuration provider and the Command-line configuration provider.
XML configuration provider
The xref:Microsoft.Extensions.Configuration.Xml.XmlConfigurationProvider loads configuration from XML file key-value pairs at runtime.
The following code clears all the configuration providers and adds several configuration providers:
In the preceding code, settings in the MyXMLFile.xml and MyXMLFile.Environment
.xml files are overridden by settings in the:
The sample download contains the following MyXMLFile.xml file:
The following code from the sample download displays several of the preceding configurations settings:
Repeating elements that use the same element name work if the name
attribute is used to distinguish the elements:
The following code reads the previous configuration file and displays the keys and values:
Attributes can be used to supply values:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<key attribute="value" />
<section>
<key attribute="value" />
</section>
</configuration>
The previous configuration file loads the following keys with value
:
- key:attribute
- section🔑attribute
Key-per-file configuration provider
The xref:Microsoft.Extensions.Configuration.KeyPerFile.KeyPerFileConfigurationProvider uses a directory's files as configuration key-value pairs. The key is the file name. The value contains the file's contents. The Key-per-file configuration provider is used in Docker hosting scenarios.
To activate key-per-file configuration, call the xref:Microsoft.Extensions.Configuration.KeyPerFileConfigurationBuilderExtensions.AddKeyPerFile* extension method on an instance of xref:Microsoft.Extensions.Configuration.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:
.ConfigureAppConfiguration((hostingContext, config) =>
{
var path = Path.Combine(
Directory.GetCurrentDirectory(), "path/to/files");
config.AddKeyPerFile(directoryPath: path, optional: true);
})
Memory configuration provider
The xref:Microsoft.Extensions.Configuration.Memory.MemoryConfigurationProvider uses an in-memory collection as configuration key-value pairs.
The following code adds a memory collection to the configuration system:
The following code from the sample download displays the preceding configurations settings:
In the preceding code, config.AddInMemoryCollection(Dict)
is added after the default configuration providers. For an example of ordering the configuration providers, see JSON configuration provider.
See Bind an array for another example using MemoryConfigurationProvider
.
Kestrel endpoint configuration
Kestrel specific endpoint configuration overrides all cross-server endpoint configurations. Cross-server endpoint configurations include:
- UseUrls
--urls
on the command line- The environment variable
ASPNETCORE_URLS
Consider the following appsettings.json file used in an ASP.NET Core web app:
When the preceding highlighted markup is used in an ASP.NET Core web app and the app is launched on the command line with the following cross-server endpoint configuration:
dotnet run --urls="https://localhost:7777"
Kestrel binds to the endpoint configured specifically for Kestrel in the appsettings.json file (https://localhost:9999
) and not https://localhost:7777
.
Consider the Kestrel specific endpoint configured as an environment variable:
set Kestrel__Endpoints__Https__Url=https://localhost:8888
In the preceding environment variable, Https
is the name of the Kestrel specific endpoint. The preceding appsettings.json file also defines a Kestrel specific endpoint named Https
. By default, environment variables using the Environment Variables configuration provider are read after appsettings.Environment
.json, therefore, the preceding environment variable is used for the Https
endpoint.
GetValue
ConfigurationBinder.GetValue<T>
extracts a single value from configuration with a specified key and converts it to the specified type:
In the preceding code, if NumberKey
isn't found in the configuration, the default value of 99
is used.
GetSection, GetChildren, and Exists
For the examples that follow, consider the following MySubsection.json file:
The following code adds MySubsection.json to the configuration providers:
GetSection
IConfiguration.GetSection returns a configuration subsection with the specified subsection key.
The following code returns values for section1
:
The following code returns values for section2:subsection0
:
GetSection
never returns null
. If a matching section isn't found, an empty IConfigurationSection
is returned.
When GetSection
returns a matching section, xref:Microsoft.Extensions.Configuration.IConfigurationSection.Value isn't populated. A xref:Microsoft.Extensions.Configuration.IConfigurationSection.Key and xref:Microsoft.Extensions.Configuration.IConfigurationSection.Path are returned when the section exists.
GetChildren and Exists
The following code calls IConfiguration.GetChildren and returns values for section2:subsection0
:
The preceding code calls ConfigurationExtensions.Exists to verify the section exists:
Bind an array
The ConfigurationBinder.Bind supports binding arrays to objects using array indices in configuration keys. Any array format that exposes a numeric key segment is capable of array binding to a POCO class array.
Consider MyArray.json from the sample download:
The following code adds MyArray.json to the configuration providers:
The following code reads the configuration and displays the values:
The preceding code returns the following output:
Index: 0 Value: value00
Index: 1 Value: value10
Index: 2 Value: value20
Index: 3 Value: value40
Index: 4 Value: value50
In the preceding output, Index 3 has value value40
, corresponding to "4": "value40",
in MyArray.json. The bound array indices are continuous and not bound to the configuration key index. The configuration binder isn't capable of binding null values or creating null entries in bound objects.
Custom configuration provider
The sample app demonstrates how to create a basic configuration provider that reads configuration key-value pairs from a database using Entity Framework (EF).
The provider has the following characteristics:
- The EF in-memory database is used for demonstration purposes. To use a database that requires a connection string, implement a secondary
ConfigurationBuilder
to supply the connection string from another configuration provider. - The provider reads a database table into configuration at startup. The provider doesn't query the database on a per-key basis.
- Reload-on-change isn't implemented, so updating the database after the app starts has no effect on the app's configuration.
Define an EFConfigurationValue
entity for storing configuration values in the database.
Models/EFConfigurationValue.cs:
Add an EFConfigurationContext
to store and access the configured values.
EFConfigurationProvider/EFConfigurationContext.cs:
Create a class that implements xref:Microsoft.Extensions.Configuration.IConfigurationSource.
EFConfigurationProvider/EFConfigurationSource.cs:
Create the custom configuration provider by inheriting from xref:Microsoft.Extensions.Configuration.ConfigurationProvider. The configuration provider initializes the database when it's empty. Since configuration keys are case-insensitive, the dictionary used to initialize the database is created with the case-insensitive comparer (StringComparer.OrdinalIgnoreCase).
EFConfigurationProvider/EFConfigurationProvider.cs:
An AddEFConfiguration
extension method permits adding the configuration source to a ConfigurationBuilder
.
Extensions/EntityFrameworkExtensions.cs:
The following code shows how to use the custom EFConfigurationProvider
in Program.cs:
Access configuration with Dependency Injection (DI)
Configuration can be injected into services using Dependency Injection (DI) by resolving the xref:Microsoft.Extensions.Configuration.IConfiguration service:
For information on how to access values using IConfiguration
, see GetValue and GetSection, GetChildren, and Exists in this article.
Access configuration in Razor Pages
The following code displays configuration data in a Razor Page:
In the following code, MyOptions
is added to the service container with xref:Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure* and bound to configuration:
The following markup uses the @inject
Razor directive to resolve and display the options values:
Access configuration in a MVC view file
The following code displays configuration data in a MVC view:
Configure options with a delegate
Options configured in a delegate override values set in the configuration providers.
In the following code, an xref:Microsoft.Extensions.Options.IConfigureOptions%601 service is added to the service container. It uses a delegate to configure values for MyOptions
:
The following code displays the options values:
In the preceding example, the values of Option1
and Option2
are specified in appsettings.json and then overridden by the configured delegate.
Host versus app configuration
Before the app is configured and started, a host is configured and launched. The host is responsible for app startup and lifetime management. Both the app and the host are configured using the configuration providers described in this topic. Host configuration key-value pairs are also included in the app's configuration. For more information on how the configuration providers are used when the host is built and how configuration sources affect host configuration, see xref:fundamentals/index#host.
Default host configuration
For details on the default configuration when using the Web Host, see the ASP.NET Core 2.2 version of this topic.
- Host configuration is provided from:
- Environment variables prefixed with
DOTNET_
(for example,DOTNET_ENVIRONMENT
) using the Environment Variables configuration provider. The prefix (DOTNET_
) is stripped when the configuration key-value pairs are loaded. - Command-line arguments using the Command-line configuration provider.
- Environment variables prefixed with
- Web Host default configuration is established (
ConfigureWebHostDefaults
):- Kestrel is used as the web server and configured using the app's configuration providers.
- Add Host Filtering Middleware.
- Add Forwarded Headers Middleware if the
ASPNETCORE_FORWARDEDHEADERS_ENABLED
environment variable is set totrue
. - Enable IIS integration.
Other configuration
This topic only pertains to app configuration. Other aspects of running and hosting ASP.NET Core apps are configured using configuration files not covered in this topic:
- launch.json/launchSettings.json are tooling configuration files for the Development environment, described:
- In xref:fundamentals/environments#development.
- Across the documentation set where the files are used to configure ASP.NET Core apps for Development scenarios.
- web.config is a server configuration file, described in the following topics:
Environment variables set in launchSettings.json override those set in the system environment.
For more information on migrating app configuration from earlier versions of ASP.NET, see xref:migration/proper-to-2x/index#store-configurations.
Add configuration from an external assembly
An xref:Microsoft.AspNetCore.Hosting.IHostingStartup implementation allows adding enhancements to an app at startup from an external assembly outside of the app's Startup
class. For more information, see xref:fundamentals/configuration/platform-specific-configuration.
Additional resources
- Configuration source code
- xref:fundamentals/configuration/options
- xref:blazor/fundamentals/configuration
::: moniker-end
::: moniker range=">= aspnetcore-3.1 < aspnetcore-6.0"
Configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources:
- Settings files, such as appsettings.json
- Environment variables
- Azure Key Vault
- Azure App Configuration
- Command-line arguments
- Custom providers, installed or created
- Directory files
- In-memory .NET objects
This topic provides information on configuration in ASP.NET Core. For information on using configuration in console apps, see .NET Configuration.
View or download sample code (how to download)
Default configuration
ASP.NET Core web apps created with dotnet new or Visual Studio generate the following code:
xref:Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder* provides default configuration for the app in the following order:
- ChainedConfigurationProvider : Adds an existing
IConfiguration
as a source. In the default configuration case, adds the host configuration and setting it as the first source for the app configuration. - appsettings.json using the JSON configuration provider.
- appsettings.
Environment
.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json. - App secrets when the app runs in the
Development
environment. - Environment variables using the Environment Variables configuration provider.
- Command-line arguments using the Command-line configuration provider.
Configuration providers that are added later override previous key settings. For example, if MyKey
is set in both appsettings.json and the environment, the environment value is used. Using the default configuration providers, the Command-line configuration provider overrides all other providers.
For more information on CreateDefaultBuilder
, see Default builder settings.
The following code displays the enabled configuration providers in the order they were added:
appsettings.json
Consider the following appsettings.json file:
The following code from the sample download displays several of the preceding configurations settings:
The default xref:Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider loads configuration in the following order:
- appsettings.json
- appsettings.
Environment
.json : For example, the appsettings.Production.json and appsettings.Development.json files. The environment version of the file is loaded based on the IHostingEnvironment.EnvironmentName. For more information, see xref:fundamentals/environments.
appsettings.Environment
.json values override keys in appsettings.json. For example, by default:
- In development, appsettings.Development.json configuration overwrites values found in appsettings.json.
- In production, appsettings.Production.json configuration overwrites values found in appsettings.json. For example, when deploying the app to Azure.
If a configuration value must be guaranteed, see GetValue. The preceding example only reads strings and doesn’t support a default value.
Using the default configuration, the appsettings.json and appsettings.Environment
.json files are enabled with reloadOnChange: true. Changes made to the appsettings.json and appsettings.Environment
.json file after the app starts are read by the JSON configuration provider.
Bind hierarchical configuration data using the options pattern
Using the default configuration, the appsettings.json and appsettings.Environment
.json files are enabled with reloadOnChange: true. Changes made to the appsettings.json and appsettings.Environment
.json file after the app starts are read by the JSON configuration provider.
See JSON configuration provider in this document for information on adding additional JSON configuration files.
Combining service collection
Security and user secrets
Configuration data guidelines:
- Never store passwords or other sensitive data in configuration provider code or in plain text configuration files. The Secret Manager tool can be used to store secrets in development.
- Don't use production secrets in development or test environments.
- Specify secrets outside of the project so that they can't be accidentally committed to a source code repository.
By default, the user secrets configuration source is registered after the JSON configuration sources. Therefore, user secrets keys take precedence over keys in appsettings.json and appsettings.Environment
.json.
For more information on storing passwords or other sensitive data:
- xref:fundamentals/environments
- xref:security/app-secrets: Includes advice on using environment variables to store sensitive data. The Secret Manager tool uses the File configuration provider to store user secrets in a JSON file on the local system.
Azure Key Vault safely stores app secrets for ASP.NET Core apps. For more information, see xref:security/key-vault-configuration.
Environment variables
Using the default configuration, the xref:Microsoft.Extensions.Configuration.EnvironmentVariables.EnvironmentVariablesConfigurationProvider loads configuration from environment variable key-value pairs after reading appsettings.json, appsettings.Environment
.json, and user secrets. Therefore, key values read from the environment override values read from appsettings.json, appsettings.Environment
.json, and user secrets.
The following set
commands:
- Set the environment keys and values of the preceding example on Windows.
- Test the settings when using the sample download. The
dotnet run
command must be run in the project directory.
set MyKey="My key from Environment"
set Position__Title=Environment_Editor
set Position__Name=Environment_Rick
dotnet run
The preceding environment settings:
- Are only set in processes launched from the command window they were set in.
- Won't be read by browsers launched with Visual Studio.
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.
setx MyKey "My key from setx Environment" /M
setx Position__Title Environment_Editor /M
setx Position__Name Environment_Rick /M
To test that the preceding commands override appsettings.json and appsettings.Environment
.json:
- With Visual Studio: Exit and restart Visual Studio.
- With the CLI: Start a new command window and enter
dotnet run
.
Call xref:Microsoft.Extensions.Configuration.EnvironmentVariablesExtensions.AddEnvironmentVariables* with a string to specify a prefix for environment variables:
In the preceding code:
config.AddEnvironmentVariables(prefix: "MyCustomPrefix_")
is added after the default configuration providers. For an example of ordering the configuration providers, see JSON configuration provider.- Environment variables set with the
MyCustomPrefix_
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 following commands test the custom prefix:
set MyCustomPrefix_MyKey="My key with MyCustomPrefix_ Environment"
set MyCustomPrefix_Position__Title=Editor_with_customPrefix
set MyCustomPrefix_Position__Name=Environment_Rick_cp
dotnet run
The default configuration loads environment variables and command line arguments prefixed with DOTNET_
and ASPNETCORE_
. The DOTNET_
and ASPNETCORE_
prefixes are used by ASP.NET Core for host and app configuration, but not for user configuration. For more information on host and app configuration, see .NET Generic Host.
On Azure App Service, select New application setting on the Settings > Configuration page. Azure App Service application settings are:
- Encrypted at rest and transmitted over an encrypted channel.
- Exposed as environment variables.
For more information, see Azure Apps: Override app configuration using the Azure Portal.
See Connection string prefixes for information on Azure database connection strings.
Naming of environment variables
Environment variable names reflect the structure of an appsettings.json file. Each element in the hierarchy is separated by a double underscore (preferable) or a colon. When the element structure includes an array, the array index should be treated as an additional element name in this path. Consider the following appsettings.json file and its equivalent values represented as environment variables.
appsettings.json
{
"SmtpServer": "smtp.example.com",
"Logging": [
{
"Name": "ToEmail",
"Level": "Critical",
"Args": {
"FromAddress": "MySystem@example.com",
"ToAddress": "SRE@example.com"
}
},
{
"Name": "ToConsole",
"Level": "Information"
}
]
}
environment variables
setx SmtpServer=smtp.example.com
setx Logging__0__Name=ToEmail
setx Logging__0__Level=Critical
setx Logging__0__Args__FromAddress=MySystem@example.com
setx Logging__0__Args__ToAddress=SRE@example.com
setx Logging__1__Name=ToConsole
setx Logging__1__Level=Information
Environment variables set in generated launchSettings.json
Environment variables set in launchSettings.json override those set in the system environment. For example, the ASP.NET Core web templates generate a launchSettings.json file that sets the endpoint configuration to:
"applicationUrl": "https://localhost:5001;http://localhost:5000"
Configuring the applicationUrl
sets the ASPNETCORE_URLS
environment variable and overrides values set in the environment.
Escape environment variables on Linux
On Linux, the value of URL environment variables must be escaped so systemd
can parse it. Use the linux tool systemd-escape
which yields http:--localhost:5001
groot@terminus:~$ systemd-escape http://localhost:5001
http:--localhost:5001
Display environment variables
The following code displays the environment variables and values on application startup, which can be helpful when debugging environment settings:
Command-line
Using the default configuration, the xref:Microsoft.Extensions.Configuration.CommandLine.CommandLineConfigurationProvider loads configuration from command-line argument key-value pairs after the following configuration sources:
- appsettings.json and appsettings.
Environment
.json files. - App secrets 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.
Command-line arguments
The following command sets keys and values using =
:
dotnet run MyKey="My key from command line" Position:Title=Cmd Position:Name=Cmd_Rick
The following command sets keys and values using /
:
dotnet run /MyKey "Using /" /Position:Title=Cmd_ /Position:Name=Cmd_Rick
The following command sets keys and values using --
:
dotnet run --MyKey "Using --" --Position:Title=Cmd-- --Position:Name=Cmd--Rick
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,MySetting=
.
Within the same command, don't mix command-line argument key-value pairs that use =
with key-value pairs that use a space.
Switch mappings
Switch mappings allow key name replacement logic. Provide a dictionary of switch replacements to the xref:Microsoft.Extensions.Configuration.CommandLineConfigurationExtensions.AddCommandLine* method.
When the switch mappings dictionary is used, the dictionary is checked for a key that matches the key provided by a command-line argument. If the command-line key is found in the dictionary, the dictionary value is passed back to set the key-value pair into the app's configuration. A switch mapping is required for any command-line key prefixed with a single dash (-
).
Switch mappings dictionary key rules:
- Switches must start with
-
or--
. - The switch mappings dictionary must not contain duplicate keys.
To use a switch mappings dictionary, pass it into the call to AddCommandLine
:
The following code shows the key values for the replaced keys:
The following command works to test key replacement:
dotnet run -k1 value1 -k2 value2 --alt3=value2 /alt4=value3 --alt5 value5 /alt6 value6
For apps that use switch mappings, the call to CreateDefaultBuilder
shouldn't pass arguments. The CreateDefaultBuilder
method's AddCommandLine
call doesn't include mapped switches, and there's no way to pass the switch-mapping dictionary to CreateDefaultBuilder
. The solution isn't to pass the arguments to CreateDefaultBuilder
but instead to allow the ConfigurationBuilder
method's AddCommandLine
method to process both the arguments and the switch-mapping dictionary.
Set environment and command-line arguments with Visual Studio
The following image shows setting environment and command-line arguments with Visual Studio:
In Visual Studio 2019 version 16.10 preview 4 and later, setting environment and command-line arguments is done from the launch profiles UI:
Hierarchical configuration data
The Configuration API reads hierarchical configuration data by flattening the hierarchical data with the use of a delimiter in the configuration keys.
The sample download contains the following appsettings.json file:
The following code from the sample download displays several of the configurations settings:
The preferred way to read hierarchical configuration data is using the options pattern. For more information, see Bind hierarchical configuration data in this document.
xref:Microsoft.Extensions.Configuration.ConfigurationSection.GetSection* and xref:Microsoft.Extensions.Configuration.IConfiguration.GetChildren* methods are available to isolate sections and children of a section in the configuration data. These methods are described later in GetSection, GetChildren, and Exists.
Configuration keys and values
Configuration keys:
- Are case-insensitive. For example,
ConnectionString
andconnectionstring
are treated as equivalent keys. - If a key and value is set in more than one configuration providers, the value from the last provider added is used. For more information, see Default configuration.
- Hierarchical keys
- Within the Configuration API, a colon separator (
:
) works on all platforms. - In environment variables, a colon separator may not work on all platforms. A double underscore,
__
, is supported by all platforms and is automatically converted into a colon:
. - In Azure Key Vault, hierarchical keys use
--
as a separator. The Azure Key Vault configuration provider automatically replaces--
with a:
when the secrets are loaded into the app's configuration.
- Within the Configuration API, a colon separator (
- The xref:Microsoft.Extensions.Configuration.ConfigurationBinder supports binding arrays to objects using array indices in configuration keys. Array binding is described in the Bind an array to a class section.
Configuration values:
- Are strings.
- Null values can't be stored in configuration or bound to objects.
Configuration providers
The following table shows the configuration providers available to ASP.NET Core apps.
Provider | Provides configuration from |
---|---|
Azure Key Vault configuration provider | Azure Key Vault |
Azure App configuration provider | Azure App Configuration |
Command-line configuration provider | Command-line parameters |
Custom configuration provider | Custom source |
Environment Variables configuration provider | Environment variables |
File configuration provider | INI, JSON, and XML files |
Key-per-file configuration provider | Directory files |
Memory configuration provider | In-memory collections |
User secrets | File in the user profile directory |
Configuration sources are read in the order that their configuration providers are specified. Order configuration providers in code to suit the priorities for the underlying configuration sources that the app requires.
A typical sequence of configuration providers is:
- appsettings.json
- appsettings.
Environment
.json - User secrets
- Environment variables using the Environment Variables configuration provider.
- Command-line arguments using the Command-line configuration provider.
A common practice is to add the Command-line configuration provider last in a series of providers to allow command-line arguments to override configuration set by the other providers.
The preceding sequence of providers is used in the default configuration.
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
.
Connection string prefix | Provider |
---|---|
CUSTOMCONNSTR_ |
Custom provider |
MYSQLCONNSTR_ |
MySQL |
SQLAZURECONNSTR_ |
Azure SQL Database |
SQLCONNSTR_ |
SQL Server |
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).
Environment variable key | Converted configuration key | Provider configuration entry |
---|---|---|
CUSTOMCONNSTR_{KEY} |
ConnectionStrings:{KEY} |
Configuration entry not created. |
MYSQLCONNSTR_{KEY} |
ConnectionStrings:{KEY} |
Key: ConnectionStrings:{KEY}_ProviderName :Value: MySql.Data.MySqlClient |
SQLAZURECONNSTR_{KEY} |
ConnectionStrings:{KEY} |
Key: ConnectionStrings:{KEY}_ProviderName :Value: System.Data.SqlClient |
SQLCONNSTR_{KEY} |
ConnectionStrings:{KEY} |
Key: ConnectionStrings:{KEY}_ProviderName :Value: System.Data.SqlClient |
File configuration provider
xref:Microsoft.Extensions.Configuration.FileConfigurationProvider is the base class for loading configuration from the file system. The following configuration providers derive from FileConfigurationProvider
:
INI configuration provider
The xref:Microsoft.Extensions.Configuration.Ini.IniConfigurationProvider loads configuration from INI file key-value pairs at runtime.
The following code clears all the configuration providers and adds several configuration providers:
In the preceding code, settings in the MyIniConfig.ini and MyIniConfig.Environment
.ini files are overridden by settings in the:
The sample download contains the following MyIniConfig.ini file:
The following code from the sample download displays several of the preceding configurations settings:
JSON configuration provider
The xref:Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider loads configuration from JSON file key-value pairs.
Overloads can specify:
- Whether the file is optional.
- Whether the configuration is reloaded if the file changes.
Consider the following code:
The preceding code:
- Configures the JSON configuration provider to load the MyConfig.json file with the following options:
optional: true
: The file is optional.reloadOnChange: true
: The file is reloaded when changes are saved.
- Reads the default configuration providers before the MyConfig.json file. Settings in the MyConfig.json file override setting in the default configuration providers, including the Environment variables configuration provider and the Command-line configuration provider.
You typically don't want a custom JSON file overriding values set in the Environment variables configuration provider and the Command-line configuration provider.
The following code clears all the configuration providers and adds several configuration providers:
In the preceding code, settings in the MyConfig.json and MyConfig.Environment
.json files:
- Override settings in the appsettings.json and appsettings.
Environment
.json files. - Are overridden by settings in the Environment variables configuration provider and the Command-line configuration provider.
The sample download contains the following MyConfig.json file:
The following code from the sample download displays several of the preceding configurations settings:
XML configuration provider
The xref:Microsoft.Extensions.Configuration.Xml.XmlConfigurationProvider loads configuration from XML file key-value pairs at runtime.
The following code clears all the configuration providers and adds several configuration providers:
In the preceding code, settings in the MyXMLFile.xml and MyXMLFile.Environment
.xml files are overridden by settings in the:
The sample download contains the following MyXMLFile.xml file:
The following code from the sample download displays several of the preceding configurations settings:
Repeating elements that use the same element name work if the name
attribute is used to distinguish the elements:
The following code reads the previous configuration file and displays the keys and values:
Attributes can be used to supply values:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<key attribute="value" />
<section>
<key attribute="value" />
</section>
</configuration>
The previous configuration file loads the following keys with value
:
- key:attribute
- section🔑attribute
Key-per-file configuration provider
The xref:Microsoft.Extensions.Configuration.KeyPerFile.KeyPerFileConfigurationProvider uses a directory's files as configuration key-value pairs. The key is the file name. The value contains the file's contents. The Key-per-file configuration provider is used in Docker hosting scenarios.
To activate key-per-file configuration, call the xref:Microsoft.Extensions.Configuration.KeyPerFileConfigurationBuilderExtensions.AddKeyPerFile* extension method on an instance of xref:Microsoft.Extensions.Configuration.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:
.ConfigureAppConfiguration((hostingContext, config) =>
{
var path = Path.Combine(
Directory.GetCurrentDirectory(), "path/to/files");
config.AddKeyPerFile(directoryPath: path, optional: true);
})
Memory configuration provider
The xref:Microsoft.Extensions.Configuration.Memory.MemoryConfigurationProvider uses an in-memory collection as configuration key-value pairs.
The following code adds a memory collection to the configuration system:
The following code from the sample download displays the preceding configurations settings:
In the preceding code, config.AddInMemoryCollection(Dict)
is added after the default configuration providers. For an example of ordering the configuration providers, see JSON configuration provider.
See Bind an array for another example using MemoryConfigurationProvider
.
::: moniker-end ::: moniker range=">= aspnetcore-5.0 < aspnetcore-6.0"
Kestrel endpoint configuration
Kestrel specific endpoint configuration overrides all cross-server endpoint configurations. Cross-server endpoint configurations include:
- UseUrls
--urls
on the command line- The environment variable
ASPNETCORE_URLS
Consider the following appsettings.json file used in an ASP.NET Core web app:
When the preceding highlighted markup is used in an ASP.NET Core web app and the app is launched on the command line with the following cross-server endpoint configuration:
dotnet run --urls="https://localhost:7777"
Kestrel binds to the endpoint configured specifically for Kestrel in the appsettings.json file (https://localhost:9999
) and not https://localhost:7777
.
Consider the Kestrel specific endpoint configured as an environment variable:
set Kestrel__Endpoints__Https__Url=https://localhost:8888
In the preceding environment variable, Https
is the name of the Kestrel specific endpoint. The preceding appsettings.json file also defines a Kestrel specific endpoint named Https
. By default, environment variables using the Environment Variables configuration provider are read after appsettings.Environment
.json, therefore, the preceding environment variable is used for the Https
endpoint.
::: moniker-end ::: moniker range=">= aspnetcore-3.0 < aspnetcore-6.0"
GetValue
ConfigurationBinder.GetValue<T>
extracts a single value from configuration with a specified key and converts it to the specified type. This method is an extension method for xref:Microsoft.Extensions.Configuration.IConfiguration:
In the preceding code, if NumberKey
isn't found in the configuration, the default value of 99
is used.
GetSection, GetChildren, and Exists
For the examples that follow, consider the following MySubsection.json file:
The following code adds MySubsection.json to the configuration providers:
GetSection
IConfiguration.GetSection returns a configuration subsection with the specified subsection key.
The following code returns values for section1
:
The following code returns values for section2:subsection0
:
GetSection
never returns null
. If a matching section isn't found, an empty IConfigurationSection
is returned.
When GetSection
returns a matching section, xref:Microsoft.Extensions.Configuration.IConfigurationSection.Value isn't populated. A xref:Microsoft.Extensions.Configuration.IConfigurationSection.Key and xref:Microsoft.Extensions.Configuration.IConfigurationSection.Path are returned when the section exists.
GetChildren and Exists
The following code calls IConfiguration.GetChildren and returns values for section2:subsection0
:
The preceding code calls ConfigurationExtensions.Exists to verify the section exists:
Bind an array
The ConfigurationBinder.Bind supports binding arrays to objects using array indices in configuration keys. Any array format that exposes a numeric key segment is capable of array binding to a POCO class array.
Consider MyArray.json from the sample download:
The following code adds MyArray.json to the configuration providers:
The following code reads the configuration and displays the values:
The preceding code returns the following output:
Index: 0 Value: value00
Index: 1 Value: value10
Index: 2 Value: value20
Index: 3 Value: value40
Index: 4 Value: value50
In the preceding output, Index 3 has value value40
, corresponding to "4": "value40",
in MyArray.json. The bound array indices are continuous and not bound to the configuration key index. The configuration binder isn't capable of binding null values or creating null entries in bound objects
The following code loads the array:entries
configuration with the xref:Microsoft.Extensions.Configuration.MemoryConfigurationBuilderExtensions.AddInMemoryCollection* extension method:
The following code reads the configuration in the arrayDict
Dictionary
and displays the values:
The preceding code returns the following output:
Index: 0 Value: value0
Index: 1 Value: value1
Index: 2 Value: value2
Index: 3 Value: value4
Index: 4 Value: value5
Index #3 in the bound object holds the configuration data for the array:4
configuration key and its value of value4
. When configuration data containing an array is bound, the array indices in the configuration keys are used to iterate the configuration data when creating the object. A null value can't be retained in configuration data, and a null-valued entry isn't created in a bound object when an array in configuration keys skip one or more indices.
The missing configuration item for index #3 can be supplied before binding to the ArrayExample
instance by any configuration provider that reads the index #3 key/value pair. Consider the following Value3.json file from the sample download:
The following code includes configuration for Value3.json and the arrayDict
Dictionary
:
The following code reads the preceding configuration and displays the values:
The preceding code returns the following output:
Index: 0 Value: value0
Index: 1 Value: value1
Index: 2 Value: value2
Index: 3 Value: value3
Index: 4 Value: value4
Index: 5 Value: value5
Custom configuration providers aren't required to implement array binding.
Custom configuration provider
The sample app demonstrates how to create a basic configuration provider that reads configuration key-value pairs from a database using Entity Framework (EF).
The provider has the following characteristics:
- The EF in-memory database is used for demonstration purposes. To use a database that requires a connection string, implement a secondary
ConfigurationBuilder
to supply the connection string from another configuration provider. - The provider reads a database table into configuration at startup. The provider doesn't query the database on a per-key basis.
- Reload-on-change isn't implemented, so updating the database after the app starts has no effect on the app's configuration.
Define an EFConfigurationValue
entity for storing configuration values in the database.
Models/EFConfigurationValue.cs:
Add an EFConfigurationContext
to store and access the configured values.
EFConfigurationProvider/EFConfigurationContext.cs:
Create a class that implements xref:Microsoft.Extensions.Configuration.IConfigurationSource.
EFConfigurationProvider/EFConfigurationSource.cs:
Create the custom configuration provider by inheriting from xref:Microsoft.Extensions.Configuration.ConfigurationProvider. The configuration provider initializes the database when it's empty. Since configuration keys are case-insensitive, the dictionary used to initialize the database is created with the case-insensitive comparer (StringComparer.OrdinalIgnoreCase).
EFConfigurationProvider/EFConfigurationProvider.cs:
An AddEFConfiguration
extension method permits adding the configuration source to a ConfigurationBuilder
.
Extensions/EntityFrameworkExtensions.cs:
The following code shows how to use the custom EFConfigurationProvider
in Program.cs:
Access configuration in Startup
The following code displays configuration data in Startup
methods:
For an example of accessing configuration using startup convenience methods, see App startup: Convenience methods.
Access configuration in Razor Pages
The following code displays configuration data in a Razor Page:
In the following code, MyOptions
is added to the service container with xref:Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure* and bound to configuration:
The following markup uses the @inject
Razor directive to resolve and display the options values:
Access configuration in a MVC view file
The following code displays configuration data in a MVC view:
Configure options with a delegate
Options configured in a delegate override values set in the configuration providers.
Configuring options with a delegate is demonstrated as Example 2 in the sample app.
In the following code, an xref:Microsoft.Extensions.Options.IConfigureOptions%601 service is added to the service container. It uses a delegate to configure values for MyOptions
:
The following code displays the options values:
In the preceding example, the values of Option1
and Option2
are specified in appsettings.json and then overridden by the configured delegate.
Host versus app configuration
Before the app is configured and started, a host is configured and launched. The host is responsible for app startup and lifetime management. Both the app and the host are configured using the configuration providers described in this topic. Host configuration key-value pairs are also included in the app's configuration. For more information on how the configuration providers are used when the host is built and how configuration sources affect host configuration, see xref:fundamentals/index#host.
Default host configuration
For details on the default configuration when using the Web Host, see the ASP.NET Core 2.2 version of this topic.
- Host configuration is provided from:
- Environment variables prefixed with
DOTNET_
(for example,DOTNET_ENVIRONMENT
) using the Environment Variables configuration provider. The prefix (DOTNET_
) is stripped when the configuration key-value pairs are loaded. - Command-line arguments using the Command-line configuration provider.
- Environment variables prefixed with
- Web Host default configuration is established (
ConfigureWebHostDefaults
):- Kestrel is used as the web server and configured using the app's configuration providers.
- Add Host Filtering Middleware.
- Add Forwarded Headers Middleware if the
ASPNETCORE_FORWARDEDHEADERS_ENABLED
environment variable is set totrue
. - Enable IIS integration.
Other configuration
This topic only pertains to app configuration. Other aspects of running and hosting ASP.NET Core apps are configured using configuration files not covered in this topic:
- launch.json/launchSettings.json are tooling configuration files for the Development environment, described:
- In xref:fundamentals/environments#development.
- Across the documentation set where the files are used to configure ASP.NET Core apps for Development scenarios.
- web.config is a server configuration file, described in the following topics:
Environment variables set in launchSettings.json override those set in the system environment.
For more information on migrating app configuration from earlier versions of ASP.NET, see xref:migration/proper-to-2x/index#store-configurations.
Add configuration from an external assembly
An xref:Microsoft.AspNetCore.Hosting.IHostingStartup implementation allows adding enhancements to an app at startup from an external assembly outside of the app's Startup
class. For more information, see xref:fundamentals/configuration/platform-specific-configuration.
Additional resources
- Configuration source code
- xref:fundamentals/configuration/options
- xref:blazor/fundamentals/configuration
::: moniker-end