The ASP.NET Core configuration system: IConfiguration as a merged key-value view over ordered providers, the default sources added by WebApplication.CreateBuilder, last-provider-wins precedence, case-insensitive hierarchical keys with colon, double underscore for environment variables, array indexes and reading values with GetValue, GetSection and GetConnectionString.
ASP.NET Core configuration is a layered key-value store. IConfiguration merges an ordered list of providers into one flat, case-insensitive dictionary. WebApplication.CreateBuilder adds, in order: appsettings.json, appsettings.{Environment}.json, user secrets (only in Development), environment variables and command-line arguments. When two providers set the same key, the one added last wins, so an environment variable on the server overrides the JSON file you shipped.
:, e.g. ConnectionStrings:Default.__ instead, e.g. ConnectionStrings__Default, because : is not allowed in Linux variable names.The trade-off: layering lets one build artifact run everywhere, but a value can come from five places, so you need to know the order to find out which one won.
"Configuration in ASP.NET Core is a merged view over several providers. Each provider, a JSON file, environment variables, the command line, Azure Key Vault, reads its source into flat key-value pairs, and
IConfigurationstacks them in the order they were added. When I ask for a key, the last provider that has it wins. That is the whole precedence rule.
WebApplication.CreateBuilder(args)sets up a sensible default stack:appsettings.json, thenappsettings.{Environment}.jsonsuch asappsettings.Production.json, then user secrets but only when the environment is Development, then environment variables, then command-line arguments. So the JSON in the repo holds defaults, the environment file adjusts per environment, and the platform overrides with environment variables without a rebuild. Keys are case-insensitive and hierarchical: nested JSON becomesLogging:LogLevel:Default. Environment variables can't contain a colon on Linux, so I writeLogging__LogLevel__Defaultwith a double underscore and the provider turns it back into a colon.The mistake I see is people expecting arrays or objects to merge across providers. They don't: each key is overridden on its own, so if JSON has three array items and an environment variable sets only index 0, items 1 and 2 survive. The other mistake is reading
IConfigurationwith magic strings all over the code instead of binding a section to an options class once. Configuration is the same artifact everywhere, different values per environment, and the provider order is how you get that."
| Order | Provider | Typical use | Reloads? |
|---|---|---|---|
| 1 | appsettings.json |
Defaults, committed to git, no secrets | Yes (reloadOnChange: true) |
| 2 | appsettings.{Environment}.json |
Per-environment differences | Yes |
| 3 | User secrets | Developer-only secrets, Development only | Yes |
| 4 | Environment variables | Platform overrides (App Service, Kubernetes, Container Apps) | No |
| 5 | Command-line args | One-off overrides, e.g. --urls |
No |
The host's own settings (ASPNETCORE_/DOTNET_-prefixed variables such as the environment name) are read first so the builder knows which appsettings.{Environment}.json to load.
| Source | Example of the same key |
|---|---|
| JSON | { "Payments": { "Timeout": "00:00:10" } } |
| Flattened key | Payments:Timeout |
| Environment variable | Payments__Timeout=00:00:10 |
| Command line | --Payments:Timeout=00:00:10 |
| Array item | Cors:Origins:0, Cors__Origins__0 |
| API | Use |
|---|---|
config["A:B"] |
Raw string, null if missing |
config.GetValue<int>("A:B", 5) |
Converted value with a default |
config.GetSection("A") |
A sub-tree (never null; check .Exists()) |
config.GetConnectionString("Default") |
Shorthand for ConnectionStrings:Default |
| Options pattern | Bind a section to a typed class; the preferred way |
One container image runs in test and production in Azure Australia East. appsettings.json sets Payments:TimeoutSeconds to 10; production sets Payments__TimeoutSeconds=5 as a Container Apps environment variable and the connection string comes from a Key Vault reference. No rebuild is needed to change either, and GetDebugView() in a diagnostics endpoint (Development only) shows which provider supplied each key.
Checks that the candidate knows where a configuration value comes from and how overrides work.
Green flags
: for hierarchy and __ for environment variables.Red flags
appsettings.json always has the final say.Every provider implements IConfigurationProvider and loads its source into a Dictionary<string, string?> with a case-insensitive comparer. JSON is flattened by walking the tree:
{ Keys produced
"Payments": { Payments:Timeout = "00:00:10"
"Timeout": "00:00:10", Payments:Retries = "3"
"Retries": 3, Payments:Regions:0 = "au-east"
"Regions": ["au-east","au-se"] Payments:Regions:1 = "au-se"
}
}
Types are lost at this stage: 3 becomes "3". Conversion happens later, in GetValue<T> or the binder, using TypeConverter with the invariant culture.
ConfigurationManager (the type behind builder.Configuration) keeps the providers in a list. A read walks the list from last to first and returns the first hit:
config["Payments:Timeout"]
│
├─► CommandLine not set
├─► EnvironmentVars "00:00:05" ◄── returned
├─► UserSecrets (not checked)
├─► appsettings.Production.json
└─► appsettings.json
That is why "last added wins" and why adding a JSON file with builder.Configuration.AddJsonFile(...) after CreateBuilder makes it beat environment variables.
GetSection("Payments") returns a ConfigurationSection that just prefixes keys. GetChildren() gathers the distinct next segments from every provider, which is how an array can end up with items from two providers.
The environment variable provider replaces __ with :. Without a prefix it loads every variable; AddEnvironmentVariables("MYAPP_") loads only prefixed ones and strips the prefix. Azure App Service also maps connection string settings: SQLAZURECONNSTR_Default becomes ConnectionStrings:Default.
JSON providers use a file watcher and a change token. When the file changes, the provider reloads and the root raises its own change token, which IOptionsMonitor listens to. Environment variables and command-line args are snapshots taken at start-up.
"Greeting": "from json" to appsettings.json and map / to return config["Greeting"].Greeting=from-env dotnet run, then dotnet run --Greeting=from-cli, and watch which value wins.Items__0 as an environment variable; print GetSection("Items").Get<string[]>().((IConfigurationRoot)builder.Configuration).GetDebugView() to see every key and the provider that supplied it.appsettings.json while the app runs and confirm the next request sees the new value.Reading configuration directly and seeing which provider won (the debug view is for Development only, because it prints secrets).
// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Raw reads: fine for a quick value, but prefer the options pattern for anything structured
var timeout = app.Configuration.GetValue("Payments:Timeout", TimeSpan.FromSeconds(10));
var regions = app.Configuration.GetSection("Payments:Regions").Get<string[]>() ?? [];
var cs = app.Configuration.GetConnectionString("Default"); // = ConnectionStrings:Default
app.Logger.LogInformation("Timeout {Timeout}, {RegionCount} regions", timeout, regions.Length);
if (app.Environment.IsDevelopment())
{
// Shows each key and the provider that supplied it: the fastest way to answer "why this value?"
app.MapGet("/debug/config", (IConfiguration config) =>
((IConfigurationRoot)config).GetDebugView());
}
app.Run();
// appsettings.json: defaults only, never secrets
{
"Payments": {
"Timeout": "00:00:10",
"Regions": [ "australiaeast", "australiasoutheast" ]
}
}
# Override on the server without a rebuild (double underscore = colon)
export Payments__Timeout=00:00:05
dotnet run --Payments:Regions:0=australiaeast
: in environment variable names on Linux. Why it is wrong: Most shells and Kubernetes reject or mangle it, so the override silently never arrives. Instead: Use __, which works on every OS.Items:0, Items:1 ...) is overridden separately, so setting only Items__0 replaces the first item and leaves the rest from the lower provider. Instead: Override every index, or model the list as a single delimited value you parse.CreateBuilder and expecting environment variables to still win. Why it is wrong: Providers added later win, so your file now overrides the platform. Instead: Insert the source at the right position, or re-add environment variables after it.appsettings.json. Why it is wrong: The file is committed and copied into every image. Instead: User secrets locally, Key Vault or platform secrets in Azure.payments:timeout in one place, Payments:Timeout in another) and treating them as different keys. Why it is wrong: Keys are case-insensitive, so one silently overrides the other, while file names such as appsettings.Production.json are case-sensitive on Linux. Instead: Use one convention (PascalCase sections matching your options classes) everywhere.config["Some:Key"] with magic strings throughout the code. Why it is wrong: Typos return null at run time and nothing is validated. Instead: Bind sections to options classes and validate them at start-up.The provider stack is how you get build once, deploy everywhere: the artifact carries defaults, the environment supplies differences. A senior keeps the layering boring: defaults in appsettings.json, small differences in the environment file, secrets and per-deployment values from the platform, and almost nothing on the command line. Every extra custom source is one more place to look when a value is wrong, so you add one only when it earns its keep, and you know GetDebugView() is the first tool when someone asks "where did this value come from?".
Performance and readability point the same way. Each config["A:B"] walks the providers from last to first and does string lookups, and GetValue<T> converts every time; that is cheap once, but not in a hot loop. Binding a section to an options class once gives typed, validated values, a single place to read the shape of the configuration, and no repeated parsing. Remote providers (Key Vault, App Configuration) add start-up latency, so load them once with a refresh interval rather than per request.
| Source | When it fits | Cost | When not to |
|---|---|---|---|
appsettings.json |
Safe defaults shared by all environments | Committed and visible | Secrets, per-customer values |
appsettings.{Env}.json |
Small per-environment differences | Drift between files over time | Values that differ per deployment slot or region |
| Environment variables | Platform-supplied overrides, containers | Not reloadable, flat names | Large structured config |
| Azure App Configuration / Key Vault | Shared, central or secret values | Network dependency at start-up | Tiny apps with two settings |
The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.
Properties/launchSettings.json defines launch profiles for local development: how to start the app, which URLs, and which environment variables. Visual Studio, Rider, VS Code with C# Dev Kit and dotnet run all read it, but it is not published. In this file I would flag: secrets are committed (a production connection string and API key), so they must be rotated now and moved to user secrets; the environment is Production, which switches on production behaviour and turns off user secrets, and combined with the production connection string means a developer's F5 talks to the live database; and it binds to 0.0.0.0 over plain HTTP, exposing the app to the network. I would replace it with HTTPS and HTTP profiles on localhost using Development, and add a separate production-like profile only if someone needs to test production behaviour against non-production resources.
Last updated 23 Nov 2026.