7.1 — The Configuration System: Providers and Precedence¶
← Roadmap · Section: 7. Configuration and Options Prev: 6.13 DI traps · Next: 7.2 appsettings.json
Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Configuration in ASP.NET Core is a set of key/value pairs, gathered from several providers and merged into one flat dictionary.
- Providers are loaded in order, and later ones overwrite earlier ones with the same key.
- The default order ends with environment variables and command-line arguments, which is how you override settings at deployment.
- Everything becomes a string keyed by a colon-separated path —
"Logging:LogLevel:Default".
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Configuration | a key/value store | A flat dictionary of string keys to string values, built at startup. |
| Provider | a source of settings | Something that contributes key/value pairs — a JSON file, environment variables, Key Vault. |
IConfiguration |
an interface | The merged result. Injectable. Read-only. |
IConfigurationBuilder |
an interface | Assembles providers in order, then builds the IConfiguration. |
| Precedence | the override rule | Later providers win. The last provider to supply a key decides its value. |
| Key path | a string | Nested keys flattened with colons: "Logging:LogLevel:Default". |
| Section | an IConfigurationSection |
A subtree of the configuration, addressed by a key prefix. |
GetSection |
a method | Returns a section. Never returns null — an absent section is an empty one. |
| Double underscore | an escape convention | __ in an environment variable name becomes : in the key path. |
| Reload | a provider feature | Re-reading a source when it changes. See 7.9. |
The concept¶
What replaced web.config¶
Classic ASP.NET had web.config — one XML file, on the machine, read at startup. Everything came
from there, and changing it usually meant a deployment.
ASP.NET Core replaced it with something more flexible: many sources, merged in a defined order.
The reason is deployment. The same compiled application has to run on your laptop, in a test environment, and in production, with different connection strings and different secrets. You do not want three builds — you want one build and different configuration (4.7).
So configuration is layered:
appsettings.json ← shared defaults, in source control
appsettings.{Environment}.json ← per-environment overrides, in source control
User Secrets ← local secrets, NOT in source control
Environment variables ← deployment settings and secrets
Command-line arguments ← last-minute overrides
Each layer only needs to specify what differs from the ones below it.
A picture: transparent sheets stacked on an overhead projector. The bottom sheet has the full picture. Each sheet above changes a few details. What you see is the combination, with the top sheet winning wherever they overlap.
⚠️ The rule that matters: later wins¶
This is the single most important thing to know:
Providers are loaded in order, and a later provider overwrites an earlier one with the same key.
That is why an environment variable beats appsettings.json, and why command-line arguments beat
everything. It is also why setting a value in the wrong place silently does nothing — something
later is overwriting it.
How it works¶
The simple version — the default order¶
WebApplication.CreateBuilder(args) sets this up
(4.3):
| # | Provider | Notes |
|---|---|---|
| 1 | appsettings.json |
Always loaded |
| 2 | appsettings.{Environment}.json |
Only that environment's file |
| 3 | User Secrets | Development only |
| 4 | Environment variables | |
| 5 | Command-line arguments | Highest priority |
Higher number wins. So:
Keys are flat, nested by colon¶
Configuration is not a tree — it is a flat dictionary. Nested JSON gets flattened:
{
"ConnectionStrings": {
"Default": "Server=localhost;Database=App"
},
"Orders": {
"MaxItems": 100,
"Notifications": { "Enabled": true }
}
}
becomes:
"ConnectionStrings:Default" = "Server=localhost;Database=App"
"Orders:MaxItems" = "100"
"Orders:Notifications:Enabled" = "true"
Two consequences worth noting.
Everything is a string. 100 and true are stored as "100" and "true". Conversion
happens when you read them (7.5).
Arrays become indexed keys:
⚠️ That array behaviour causes a real trap. Because merging happens key by key, overriding an array in a later provider does not replace it — it overwrites individual indices. A three-element array overridden by a one-element array leaves elements 1 and 2 from the original in place. See 7.2.
⚠️ Double underscores in environment variables¶
Environment variable names cannot contain colons on all platforms, so the convention is __:
# These are the same key
ConnectionStrings__Default="Server=prod;..." # environment variable
"ConnectionStrings:Default" # configuration key
Getting this wrong is a very common deployment mistake — a single underscore does nothing, and
there is no error. The setting is simply absent and you fall back to whatever appsettings.json
said.
How it actually works — building it yourself¶
The defaults cover almost everything, but you can add or reorder providers:
var builder = WebApplication.CreateBuilder(args);
// Added AFTER the defaults, so this wins over all of them
builder.Configuration.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: true);
// Or start from scratch
builder.Configuration.Sources.Clear();
builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args);
⚠️ Order of the Add calls is the precedence order. Adding AddEnvironmentVariables() before
AddJsonFile(...) means the JSON file wins over environment variables — which is almost certainly
not what you want, and is a genuinely confusing bug because everything looks configured correctly.
optional: false is worth using for the base file. It makes a missing appsettings.json fail
at startup rather than silently producing an application with no configuration.
Which provider supplied a value?¶
When a setting is not what you expect, this is how you find out:
That prints every key, its value, and which provider supplied it:
ConnectionStrings:
Default=Server=prod;... (EnvironmentVariablesConfigurationProvider)
Logging:
LogLevel:
Default=Warning (JsonConfigurationProvider for 'appsettings.Production.json')
⚠️ Never leave that in production code — it prints secrets. It is a debugging tool, and worth gating behind an environment check if you keep it at all.
The deeper detail — what a provider actually is¶
A provider is anything that can produce key/value pairs. The built-in ones:
| Provider | Added by |
|---|---|
| JSON file | AddJsonFile |
| Environment variables | AddEnvironmentVariables |
| Command line | AddCommandLine |
| User Secrets | AddUserSecrets |
| In-memory | AddInMemoryCollection |
| INI / XML | AddIniFile / AddXmlFile |
| Azure Key Vault | AddAzureKeyVault |
| AWS Secrets Manager | AddSecretsManager |
The in-memory one is genuinely useful in tests, because it lets you set configuration without files:
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:Default"] = "DataSource=:memory:",
["Features:EnableNewCheckout"] = "true"
});
See 20.7.
Writing your own provider is covered in 7.10.
Code¶
A realistic setup, with the reasoning inline:
var builder = WebApplication.CreateBuilder(args);
// The defaults already gave us:
// appsettings.json → appsettings.{Env}.json → User Secrets (dev) →
// env vars → command line
// Add Key Vault in production only, AFTER the defaults so it wins over files
if (builder.Environment.IsProduction())
{
builder.Configuration.AddAzureKeyVault(
new Uri($"https://{builder.Configuration["KeyVault:Name"]}.vault.azure.net/"),
new DefaultAzureCredential());
}
// Fail fast if something essential is missing, rather than at first use
var connectionString = builder.Configuration.GetConnectionString("Default")
?? throw new InvalidOperationException(
"ConnectionStrings:Default is not configured.");
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(connectionString));
var app = builder.Build();
That startup check is worth the two lines. Without it, a missing connection string surfaces as an obscure error on the first database call, potentially long after deployment.
Where each thing belongs¶
| Setting | Belongs in |
|---|---|
| Log levels, feature defaults | appsettings.json |
| Per-environment endpoints, log levels | appsettings.{Environment}.json |
| Local connection strings and API keys | User Secrets — never in source control |
| Production secrets | Key Vault or the platform's secret store |
| Deployment-specific values | Environment variables |
| One-off overrides while debugging | Command-line arguments |
⚠️ The line that matters: no real secret goes in any appsettings*.json file. Those are
committed to source control, so anything in them is in your git history permanently and visible
to everyone with repository access. See 17.7.
Interview questions¶
Q: How does configuration work in ASP.NET Core?
It is a flat dictionary of string keys to string values, built at startup by merging several
providers. The defaults are appsettings.json, then the environment-specific file, then User
Secrets in Development, then environment variables, then command-line arguments — and they are
applied in that order, with later providers overwriting earlier ones for the same key. That
layering is what lets one compiled build run in every environment with different settings, which
is the whole point compared to web.config.
Q: What is the precedence order and why does it matter?
Later providers win. So an environment variable overrides appsettings.json, and a command-line
argument overrides everything. It matters because that is how you supply deployment-specific
values and secrets without changing files that are in source control. It also explains a common
confusion — someone sets a value in appsettings.json, it has no effect, and the reason is that
an environment variable set by the hosting platform is overwriting it. GetDebugView on the
configuration root tells you which provider supplied each value, which is the fastest way to
diagnose that.
Q: How do you express a nested configuration key as an environment variable?
With double underscores. Configuration keys are colon-separated paths like
ConnectionStrings:Default, but environment variable names cannot reliably contain colons, so
the convention is ConnectionStrings__Default. Using a single underscore is a common deployment
mistake and there is no error — the variable simply is not recognised as that key, so the
application silently falls back to whatever the JSON file said.
Q: What happens to arrays in configuration?
They are flattened into indexed keys, so a three-element array becomes Key:0, Key:1, Key:2.
That causes a real trap when overriding: because merging happens per key, supplying a shorter
array in a later provider overwrites only the indices it defines and leaves the rest of the
original in place. So overriding a three-item list with a one-item list gives you the new first
item and the original second and third. If you need to replace a list entirely you have to clear
it explicitly or restructure the setting.
Traps ⚠️¶
- Later providers win. A value set in the wrong layer is silently overwritten.
- Environment variables need
__, not_. A single underscore silently does nothing. - Arrays merge by index, so a shorter override leaves the original tail elements in place.
- The order of
Addcalls is the precedence order. Adding a JSON file afterAddEnvironmentVariablesmakes the file win. - Everything is a string.
"true"and"100"are converted when read, and a bad value throws at that point. GetSectionnever returns null — an absent section is an empty one, so a typo produces silence rather than an error.GetDebugViewprints secrets. Never leave it in production code.- No secrets in
appsettings*.json. Those files are in source control.
Related¶
- 7.2 appsettings.json — the file layering in detail
- 7.3 Environment variables and User Secrets — the other providers
- 7.5 The IConfiguration API — reading values
- 7.9 Reload on change — what reloads and what does not
- 7.10 Custom providers — writing your own
- 4.7 Environments — what selects the environment file
- 17.7 Secrets management — what must not be committed