IConfiguration is the .NET interface that gives your app read access to its settings. It lives in Microsoft.Extensions.Configuration, and its job is to merge values from many sources, such as appsettings.json, appsettings.{Environment}.json, environment variables, user secrets, command-line arguments and Azure Key Vault, into one flat set of key-value pairs.
Two rules explain most of its behaviour. Hierarchical keys are joined with a colon, so {"Smtp": {"Host": "mail"}} becomes the key Smtp:Host. And when two sources define the same key, the source added later wins. In a default ASP.NET Core app, that means command-line arguments beat environment variables, which beat user secrets, which beat appsettings.{Environment}.json, which beats appsettings.json.
You can read values straight from IConfiguration, but for anything beyond startup code I'd bind sections to typed classes with the options pattern and validate them when the app starts:
var builder = WebApplication.CreateBuilder(args);
// Direct read
string? host = builder.Configuration["Smtp:Host"];
// Recommended: typed, validated options
builder.Services.AddOptions<SmtpOptions>()
.BindConfiguration(SmtpOptions.SectionName)
.ValidateDataAnnotations()
.ValidateOnStart();
The examples below target .NET 10 LTS and also apply to .NET 11.
How the values get merged
Configuration is built in two steps. Providers load their raw data, and then everything is flattened into string keys and string values. Here's what happens to a setting that appears in three places:
appsettings.json { "Smtp": { "Host": "localhost", "Port": 25 } }
appsettings.Production.json { "Smtp": { "Host": "smtp.contoso.com" } }
Environment variable Smtp__Port=587
↓ each provider flattens its data
Smtp:Host = localhost (appsettings.json)
Smtp:Host = smtp.contoso.com (Production file, added later, wins)
Smtp:Port = 587 (environment variable, added later, wins)
↓
IConfiguration["Smtp:Host"] == "smtp.contoso.com"
IConfiguration["Smtp:Port"] == "587"
A few consequences follow from that flattening. Keys are case-insensitive, so smtp:host and Smtp:Host are the same key. Every value is a string, and conversion to int, bool, TimeSpan and so on only happens when you call GetValue<T> or bind. Arrays become indexed keys such as AllowedOrigins:0 and AllowedOrigins:1. And "last provider wins" applies to each individual key, never to a whole section.
In ASP.NET Core, builder.Configuration is a ConfigurationManager. It's both a builder, so you can add sources, and an IConfiguration, so you can read from it immediately. The same object is registered in dependency injection as IConfiguration.
Which source wins
The ASP.NET Core configuration documentation gives the order in which WebApplication.CreateBuilder loads app configuration. From highest priority to lowest:
Priority | Source | Notes |
1 (highest) | Command-line arguments | Added at the start and again at the end, so they always win |
2 | Environment variables without the ASPNETCORE_ or DOTNET_ prefix | Use __ for nesting |
3 | User secrets | Only when the environment is Development |
4 | appsettings.{Environment}.json
| For example appsettings.Production.json |
5 | appsettings.json
| Base settings shared by all environments |
6 (lowest) | Host configuration | Includes DOTNET_ and ASPNETCORE_ prefixed variables |
Anything you add yourself after CreateBuilder, such as Key Vault or a custom provider, goes on top of that stack. It overrides everything in the table, command-line arguments included, unless you re-add the command-line provider afterwards. That's usually what you want for a secret store, but it can catch you out when a custom source quietly beats an environment variable you set on purpose.
The JSON files
The environment name comes from ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT). The built-in names are Development, Staging and Production, and if nothing is set the app runs as Production. Forgetting to set it on a staging server is a classic way to end up with production settings where you expected staging ones.
Keep shared settings in the base file and put only the differences in the environment file:
// appsettings.json
{
"ConnectionStrings": {
"Default": "Server=localhost;Database=Shop;Trusted_Connection=True;TrustServerCertificate=True"
},
"Smtp": {
"Host": "localhost",
"Port": 25,
"UseSsl": false,
"From": "[email protected]"
},
"Features": {
"AllowedOrigins": [ "https://contoso.com", "https://www.contoso.com" ]
}
}
// appsettings.Production.json - only the keys that differ
{
"Smtp": {
"Host": "smtp.contoso.com",
"Port": 587,
"UseSsl": true
}
}
Both files load with reloadOnChange: true by default, so edits are picked up while the app runs.
Watch out for arrays. They merge by index, not by replacement. If appsettings.json lists three origins and the Production file lists one, you still get three: index 0 is replaced and indexes 1 and 2 survive from the base file. Either define the full array in one place, or use a single delimited string and split it yourself. If you're new to the file itself, our walkthrough of using appsettings.json and IConfiguration starts from the basics.
Environment variables and the double underscore
Colons don't work in environment variable names on every platform; Bash rejects them. Use a double underscore instead, and .NET converts __ to : when it reads the variable. This works the same on Windows, Linux and macOS. A single underscore (Smtp_Host) does nothing useful, and it's one of the most common configuration bugs.
Configuration key | Environment variable |
ConnectionStrings:Default
| ConnectionStrings__Default
|
Smtp:Port
| Smtp__Port
|
Features:AllowedOrigins:0
| Features__AllowedOrigins__0
|
Logging:LogLevel:Default
| Logging__LogLevel__Default
|
# Bash
export Smtp__Host="smtp.contoso.com"
export ConnectionStrings__Default="Server=db;Database=Shop;User Id=app;Password=..."
# PowerShell (current session)
$env:Smtp__Host = "smtp.contoso.com"
# docker-compose.yml
services:
api:
image: contoso/shop-api:latest
environment:
ASPNETCORE_ENVIRONMENT: Production
Smtp__Host: smtp.contoso.com
Smtp__Port: "587"
If other software shares the host, read only variables with your own prefix. The prefix is stripped from the key:
// SHOP_Smtp__Host becomes Smtp:Host
builder.Configuration.AddEnvironmentVariables(prefix: "SHOP_");
On Azure App Service, connection strings set in the portal arrive as prefixed variables such as SQLAZURECONNSTR_Default, SQLCONNSTR_Default, POSTGRESQLCONNSTR_Default or CUSTOMCONNSTR_Default. The environment variables provider maps all of them to ConnectionStrings:Default, so GetConnectionString("Default") works without any extra code.
Secrets: user secrets locally, a vault in production
User secrets keep development credentials out of your repository by storing them as JSON in your user profile rather than the project folder:
dotnet user-secrets init
dotnet user-secrets set "Smtp:Password" "dev-password"
dotnet user-secrets set "ConnectionStrings:Default" "Server=localhost;Database=Shop;User Id=sa;Password=..."
dotnet user-secrets list
The default builder loads them only in the Development environment. They are not encrypted; they simply live outside source control. So they're not a production mechanism. In production, use environment variables from your platform's secret store, Azure Key Vault or an equivalent.
For Key Vault, install Azure.Extensions.AspNetCore.Configuration.Secrets and Azure.Identity:
using Azure.Identity;
var vaultName = builder.Configuration["KeyVaultName"];
if (!string.IsNullOrEmpty(vaultName))
{
builder.Configuration.AddAzureKeyVault(
new Uri($"https://{vaultName}.vault.azure.net/"),
new DefaultAzureCredential());
}
Secret names can't contain colons, so use -- instead: a secret named Smtp--Password becomes Smtp:Password. Run under a managed identity in Azure and you don't need a secret to reach the vault at all.
Azure App Configuration is the other Azure option, a central store for settings and feature flags shared by many apps. For ASP.NET Core, install Microsoft.Azure.AppConfiguration.AspNetCore:
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(builder.Configuration["AppConfig:Endpoint"]!), new DefaultAzureCredential())
.Select("Shop:*", LabelFilter.Null)
.ConfigureRefresh(refresh => refresh.RegisterAll());
});
builder.Services.AddAzureAppConfiguration();
var app = builder.Build();
app.UseAzureAppConfiguration(); // triggers refresh checks on incoming requests
Refresh is request-driven and checks at most every 30 seconds by default. To see refreshed values, read them through IOptionsSnapshot<T> or IOptionsMonitor<T>, not IOptions<T>.
Command-line arguments
Three formats are accepted:
dotnet run Smtp:Host=localhost Smtp:Port=2525
dotnet run --Smtp:Host localhost --Smtp:Port 2525
dotnet run /Smtp:Host localhost /Smtp:Port 2525
Switch mappings give you short aliases, and a single-dash switch has to be mapped:
var switchMappings = new Dictionary<string, string>
{
["-p"] = "Smtp:Port",
["--smtp-host"] = "Smtp:Host"
};
builder.Configuration.AddCommandLine(args, switchMappings);
// dotnet run -p 2525 --smtp-host localhost
Reading values directly
These are the APIs you'll use in startup code and infrastructure. Use the existing builder.Configuration for this; calling WebApplication.CreateBuilder a second time just to read a setting is a mistake.
IConfiguration config = builder.Configuration;
// Indexer: string or null
string? host = config["Smtp:Host"];
// GetValue<T>: converts, with an optional default
int port = config.GetValue<int>("Smtp:Port", 25);
bool useSsl = config.GetValue("Smtp:UseSsl", false);
// GetConnectionString: shorthand for ConnectionStrings:{name}
string? cs = config.GetConnectionString("Default");
// GetSection never returns null - check Exists()
IConfigurationSection smtp = config.GetSection("Smtp");
if (!smtp.Exists()) { /* section missing */ }
// GetRequiredSection throws if the section is missing
IConfigurationSection features = config.GetRequiredSection("Features");
// Children (useful for dictionaries and arrays)
foreach (IConfigurationSection origin in features.GetSection("AllowedOrigins").GetChildren())
Console.WriteLine($"{origin.Path} = {origin.Value}");
// Get<T>: create and bind a new object
SmtpOptions? options = smtp.Get<SmtpOptions>();
// Bind: fill an existing object
var existing = new SmtpOptions();
smtp.Bind(existing);
Note that GetSection never fails. GetSection("Smpt") with a typo hands you an empty section without complaint, which is why GetRequiredSection, a SectionName constant and startup validation are worth the extra keystrokes.
The binder's behaviour has also shifted in recent releases. In .NET 10, null values are preserved: a JSON null used to become an empty string that the binder treated like a missing value, but now nulls bind as nulls, empty arrays bind as empty arrays, and a null bound to a non-nullable value type sets default(T). If you're upgrading, read Microsoft's breaking change notice before you ship. .NET 11 adds a [ConfigurationIgnore] attribute so the binder skips a property, which is handy for computed properties on options classes. It also binds an empty array to a constructor parameter instead of throwing, and makes file-change detection more reliable with relative paths and missing directories.
The options pattern
Injecting IConfiguration into every service works, but it scatters magic strings across your code and makes services harder to test. The options pattern binds a section once to a typed class and injects that class instead. Typed options can also be validated at startup, which is the biggest win.
public sealed class SmtpOptions
{
public const string SectionName = "Smtp";
[Required]
public string Host { get; set; } = "";
[Range(1, 65535)]
public int Port { get; set; } = 25;
public bool UseSsl { get; set; }
[Required, EmailAddress]
public string From { get; set; } = "";
public string? Password { get; set; }
}
// Program.cs
builder.Services.AddOptions<SmtpOptions>()
.BindConfiguration(SmtpOptions.SectionName)
.ValidateDataAnnotations()
.ValidateOnStart();
// Consumer
public sealed class EmailSender(IOptions<SmtpOptions> options)
{
private readonly SmtpOptions _smtp = options.Value;
public Task SendAsync(string to, string subject, string body)
{
// use _smtp.Host, _smtp.Port ...
return Task.CompletedTask;
}
}
IOptions, IOptionsSnapshot or IOptionsMonitor?
The choice comes down to lifetime and whether you need to see changes while the app is running:
Interface | Lifetime | Sees config changes? | Named options | Use when |
IOptions<T>
| Singleton | No, value fixed at first access | No | Settings that never change while running |
IOptionsSnapshot<T>
| Scoped | Yes, recomputed once per request | Yes | Per-request consistency in scoped or transient services |
IOptionsMonitor<T>
| Singleton | Yes, CurrentValue plus OnChange callback | Yes | Singletons and background services that must react to changes |
Don't inject IOptionsSnapshot<T> into a singleton. A singleton can't depend on a scoped service, and ASP.NET Core throws when scope validation is on, which it is by default in Development. Background services are the usual case, and IOptionsMonitor<T> is the right tool there:
public sealed class CacheWarmupService : BackgroundService
{
private readonly IOptionsMonitor<CacheOptions> _options;
public CacheWarmupService(IOptionsMonitor<CacheOptions> options)
{
_options = options;
_options.OnChange(o => Console.WriteLine($"Cache TTL changed to {o.Ttl}"));
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(_options.CurrentValue.Ttl, stoppingToken);
}
}
}
When you need two configurations of the same class, use named options and ask the monitor for the one you want:
builder.Services.Configure<StorageOptions>("Images", builder.Configuration.GetSection("Storage:Images"));
builder.Services.Configure<StorageOptions>("Backups", builder.Configuration.GetSection("Storage:Backups"));
public sealed class BackupJob(IOptionsMonitor<StorageOptions> storage)
{
private StorageOptions Backups => storage.Get("Backups");
}
Our article on the options pattern in .NET Core has more worked examples of all three interfaces.
Fail at startup, not on the first request
A missing setting should stop the app when it starts, not throw on the first customer request three hours later. Without ValidateOnStart(), validation only runs when the options are first resolved, so always add it. Since .NET 8 there's also a shorthand, builder.Services.AddOptionsWithValidateOnStart<SmtpOptions>().
Data annotations cover simple rules, and Validate handles one-liners that involve more than one property:
builder.Services.AddOptions<SmtpOptions>()
.BindConfiguration(SmtpOptions.SectionName)
.ValidateDataAnnotations()
.Validate(o => !o.UseSsl || o.Port != 25, "Port 25 can't be used with SSL.")
.ValidateOnStart();
For anything more involved, implement IValidateOptions<T> and register it:
public sealed class SmtpOptionsValidator : IValidateOptions<SmtpOptions>
{
public ValidateOptionsResult Validate(string? name, SmtpOptions options)
{
if (options.UseSsl && string.IsNullOrEmpty(options.Password))
return ValidateOptionsResult.Fail("Smtp:Password is required when UseSsl is true.");
return ValidateOptionsResult.Success;
}
}
builder.Services.AddSingleton<IValidateOptions<SmtpOptions>, SmtpOptionsValidator>();
If you publish trimmed or Native AOT apps, let a source generator write the validator. It reads the data annotations at build time, so validation needs no reflection:
[OptionsValidator]
public partial class SmtpOptionsGeneratedValidator : IValidateOptions<SmtpOptions>
{
}
.NET 11 adds asynchronous validation for checks that need I/O, such as confirming a host is reachable. According to the .NET 11 libraries release notes, you implement IAsyncValidateOptions<T>, startup validation runs through the new IAsyncStartupValidator, and IStartupValidator is now obsolete:
public sealed class BackendOptionsValidator : IAsyncValidateOptions<BackendOptions>
{
public async Task<ValidateOptionsResult> ValidateAsync(
string? name, BackendOptions options, CancellationToken cancellationToken = default) =>
await IsReachableAsync(options.HostName, cancellationToken)
? ValidateOptionsResult.Success
: ValidateOptionsResult.Fail($"'{options.HostName}' isn't reachable.");
public ValidateOptionsResult Validate(string? name, BackendOptions options) =>
ValidateOptionsResult.Fail("Backend validation must run asynchronously.");
}
Keep network checks at startup fast and give them a timeout. Otherwise one slow dependency will block your whole deployment.
Reloading while the app runs
The JSON files reload when saved, but whether your code sees the new value depends on how it reads it. IConfiguration["key"] always returns the current value. IOptions<T> never changes after first use, so don't expect it to reload. IOptionsSnapshot<T> picks up the new value on the next request, and IOptionsMonitor<T> updates CurrentValue immediately and fires OnChange. If you want the raw notification, use a change token:
ChangeToken.OnChange(
() => app.Configuration.GetReloadToken(),
() => app.Logger.LogInformation("Configuration reloaded"));
Containers complicate this. In Docker and Kubernetes, mounted files, including ConfigMaps (which are updated through symlinks), may not raise file-system events. Setting DOTNET_USE_POLLING_FILE_WATCHER=true switches the watcher to polling. Many teams skip the problem entirely and restart pods when configuration changes, which is the approach I'd default to.
Writing a custom provider
If your settings live in a database table or an internal service, write a source and a provider:
public sealed class DbConfigurationSource(string connectionString) : IConfigurationSource
{
public IConfigurationProvider Build(IConfigurationBuilder builder) =>
new DbConfigurationProvider(connectionString);
}
public sealed class DbConfigurationProvider(string connectionString) : ConfigurationProvider
{
public override void Load()
{
var data = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
using var connection = new SqlConnection(connectionString);
connection.Open();
using var command = new SqlCommand("SELECT [Key], [Value] FROM dbo.AppSettings", connection);
using var reader = command.ExecuteReader();
while (reader.Read())
data[reader.GetString(0)] = reader.IsDBNull(1) ? null : reader.GetString(1);
Data = data;
}
}
public static class DbConfigurationExtensions
{
public static IConfigurationBuilder AddDatabase(this IConfigurationBuilder builder, string connectionString) =>
builder.Add(new DbConfigurationSource(connectionString));
}
// Program.cs - after the defaults, so database values override JSON
builder.Configuration.AddDatabase(builder.Configuration.GetConnectionString("Default")!);
Store keys in the flattened Section:Key form. To support reload, refresh Data from a timer or notification and then call OnReload(). And remember the precedence rule: because this provider is added after the defaults, it overrides environment variables too.
Native AOT and the binding source generator
The classic binder uses reflection. For trimmed and Native AOT apps, turn on the configuration-binding source generator, which replaces Bind, Get<T>, Configure<T> and GetValue<T> calls with generated code:
<PropertyGroup>
<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
</PropertyGroup>
It's switched on automatically when you set PublishAot to true.
Testing code that reads configuration
Unit tests don't need files or environment variables. Build configuration from an in-memory dictionary:
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Smtp:Host"] = "test-smtp",
["Smtp:Port"] = "2525",
["Smtp:From"] = "[email protected]"
})
.Build();
var options = config.GetSection("Smtp").Get<SmtpOptions>()!;
var sender = new EmailSender(Options.Create(options));
For integration tests, override settings in your WebApplicationFactory:
public sealed class ApiFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureAppConfiguration((_, config) =>
{
config.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:Default"] = "Server=localhost,1433;Database=Shop_Test;...",
["Smtp:Host"] = "localhost"
});
});
}
}
Test your validators directly as well: build an invalid options object and assert that Validate fails with the message you expect.
When a setting has the wrong value
Start with the debug view. In Development, it lists every key, its final value and the provider that supplied it:
if (app.Environment.IsDevelopment())
{
var root = (IConfigurationRoot)app.Configuration;
Console.WriteLine(root.GetDebugView());
}
Never expose that output in production, because it includes your secrets. Then work through the usual suspects:
- The value comes from the wrong environment file: check
ASPNETCORE_ENVIRONMENT on the server.
- An environment variable is ignored: it probably uses a single underscore instead of
__.
- An array has stale entries: the environment file merged with the base file by index instead of replacing it.
- A custom provider or Key Vault overrides something you set elsewhere: it was added after the defaults, so it wins.
- A whole section binds as empty: look for a typo in the section name.
- A change doesn't show up: the consumer injects
IOptions<T>, or the file sits on a mount that doesn't raise change events.
Most of these never reach production if you bind to typed options, call ValidateOnStart, and keep secrets out of appsettings.json from the first commit.
Join the conversation! Your thoughts help the community grow.