skip to content

Provider Order & Overrides

WebApplication.CreateBuilder stacks appsettings.json, environment files, user secrets, environment variables and command-line args, and the last one wins. Interviewers ask why prod ignores a value.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

In ASP.NET Core, how do appsettings.json and appsettings.{Environment}.json combine, and how do you read a connection string from them?

level: juniorimportance: must knowfreq 78%

answer

  1. two JSON providers, later one wins
  2. merged key by key, not file by file
  3. environment name picks the second file
  4. ConnectionStrings section, GetConnectionString(name)
  5. arrays merge by index

basics

~10 s

ASP.NET Core loads appsettings.json, then appsettings.{Environment}.json, flattens both into colon-separated keys and lets the later file win key by key. GetConnectionString("Adoptions") reads ConnectionStrings:Adoptions from the merged result.

solid answer

~40 s

`WebApplication.CreateBuilder` adds two optional JSON providers: `appsettings.json` first, then `appsettings.{Environment}.json`, where the environment name (Development, Staging, Production) picks the file. Each file is flattened into keys such as `Features:OnlineApplications`, and a lookup asks the providers from last to first, so the environment file overrides only the keys it repeats; everything else falls through to the base file. Keys are case-insensitive. A connection string lives under the `ConnectionStrings` section and `builder.Configuration.GetConnectionString("Adoptions")` is shorthand for `GetSection("ConnectionStrings")["Adoptions"]`; it returns `null` when nothing defines it. Two traps: arrays are merged by index, not replaced, and both files are optional, so a misnamed file is silently skipped.

code

json · 7 lines
json
// appsettings.Production.json
{
  "Features": {
    "OnlineApplications": false
  },
  "Shelters": [ "central" ]
}

go deeper

for a junior

Recall the two file names, that the environment name picks the second, and that GetConnectionString reads the ConnectionStrings section. Say the later file wins per key.

for a middle

Explain the flattening into colon keys, the last-provider-first lookup and why an array overrides by index. Mention that both files are optional and keys ignore case.

for a senior

Treat the files as the bottom of a longer chain: an env var or argument beats them. Show how you fail fast on a null connection string and keep per-environment lists out of the base file.

for a principal

Decide which settings belong in committed files versus the platform, so per-environment differences stay small, reviewable and never contain credentials.

## Two files, one merged view A project created with `dotnet new webapi` ships with `appsettings.json` and `appsettings.Development.json`. `WebApplication.CreateBuilder(args)` registers a **JSON configuration provider** for each, in this order: 1. `appsettings.json` - settings shared by every environment. 2. `appsettings.{Environment}.json` - where `{Environment}` is the host's environment name, such as `Development`, `Staging` or `Production`. Both are registered with `optional: true`. A missing file is not an error; the provider simply contributes no keys. That also means a file named for an environment the app never runs in is ignored without a word. ## How the merge actually works Each JSON provider **flattens** its file into a dictionary of string keys and string values. Nested objects become colon-separated paths, and array elements become numbered segments: - `{ "Features": { "OnlineApplications": true } }` becomes `Features:OnlineApplications = "true"`. - `{ "Shelters": ["north", "south"] }` becomes `Shelters:0 = "north"` and `Shelters:1 = "south"`. When code asks for a key, the configuration root walks the providers **from the last one added to the first** and returns the first value it finds. So the environment file overrides **only the keys it defines**; every other key falls through to `appsettings.json`. Nothing is replaced file-by-file or section-by-section. Lookups ignore case, so `features:onlineapplications` finds the same value. | Key | appsettings.json | appsettings.Production.json | Result in Production | |---|---|---|---| | `Features:OnlineApplications` | `true` | `false` | `false` | | `Features:VideoMeetAndGreet` | `true` | not set | `true` | | `Shelters:0` | `north` | `central` | `central` | | `Shelters:1` | `south` | not set | `south` | The last two rows are the classic trap: an array in the environment file does **not** replace the base array. Element 0 is overridden and element 1 survives, so the Production list reads `central, south`. To shrink a list per environment, keep the list out of the base file or use keyed objects instead of arrays. ## Connection strings By convention connection strings live in a top-level `ConnectionStrings` section: ```json { "ConnectionStrings": { "Adoptions": "Host=localhost;Database=adoptions;Username=dev" }, "Features": { "OnlineApplications": true } } ``` `GetConnectionString(name)` is an extension method on `IConfiguration` defined as `GetSection("ConnectionStrings")[name]`. It reads the merged view, so an override from the environment file, an environment variable or the command line is what it returns. It returns `null`, not an exception, when no source defines the name, which is why many apps fail fast: ```csharp var cs = builder.Configuration.GetConnectionString("Adoptions") ?? throw new InvalidOperationException("ConnectionStrings:Adoptions is not set."); ``` ## What sits above the two files The two JSON files are the **lowest** app sources. The default chain then adds `{ApplicationName}.settings.json` and its environment twin, user secrets (Development only), environment variables and command-line arguments, each able to override the files. A value that looks right in `appsettings.Production.json` can therefore still lose to an environment variable set by the host. ## Where the files are looked for The JSON providers resolve both names against the **content root**. Unless code sets it, the default builder uses the **current working directory** as the content root (falling back to the app's base directory only when started from the Windows system directory). Two consequences catch people: - Starting the app as `dotnet /srv/adoptions/AdoptionsApi.dll` from another directory makes the providers look in that other directory. Both files are optional, so the app starts with no file settings at all and every key reads `null` or its default. - On Linux the file system is case-sensitive, so with the environment named `Production` a file called `appsettings.production.json` is never found. Start the process from its own folder, or set the content root explicitly, and keep the file name's casing identical to the environment name. ## A .NET 10 detail about null Since .NET 10 the JSON provider keeps a JSON `null` as a real `null` instead of turning it into an empty string. Writing `"VideoMeetAndGreet": null` in the environment file therefore still counts as defining the key: the lookup stops there and returns `null`, it does not fall back to the base file's `true`. ## Interview checklist - Name both files and say the environment name chooses the second one. - Say the merge is **per key**, with the later provider winning. - Show `GetConnectionString` and say it returns `null` when unset. - Mention the array-by-index trap and that both files are optional.

  • Why does a three-item array in appsettings.json still have three items after appsettings.Production.json sets a one-item array?
    Arrays are flattened to indexed keys (`Shelters:0`, `Shelters:1`, `Shelters:2`). The Production file defines only `Shelters:0`, so it overrides that key and the other two fall through from the base file. Configuration merges keys, never whole arrays; keep per-environment lists out of the base file or use named child objects.
  • What happens if appsettings.Production.json is missing on the server?
    Nothing visible: the default builder registers both appsettings files with `optional: true`, so the provider contributes no keys and every lookup falls back to `appsettings.json` and the higher sources. Fail fast on values that must exist, for example by throwing when `GetConnectionString` returns `null`.
  • Are configuration keys case-sensitive in ASP.NET Core?
    No. Each provider stores its keys in a dictionary using an ordinal case-insensitive comparer, so `ConnectionStrings:Adoptions` and `connectionstrings:adoptions` are the same key, and an environment file overrides a base key even when the casing differs. File names are another matter: on Linux the file system decides whether `appsettings.production.json` matches.

  • appsettings.Production.json replaces appsettings.json completely when the app runs in Production.
  • An array in the environment file replaces the whole array from appsettings.json.
  • GetConnectionString throws a KeyNotFoundException when the name is not configured.
  • The environment file wins over environment variables because it is more specific.
  • A missing appsettings.Production.json makes the app fail at startup.

Assumes ASP.NET Core 10 on .NET 10; since .NET 10 the JSON provider keeps a JSON null as null instead of an empty string.

open as a page

In ASP.NET Core, how does an environment variable like ConnectionStrings__Adoptions override appsettings.json, and what do the ASPNETCORE_ and DOTNET_ prefixes change?

level: middleimportance: must knowfreq 70%

basics

~20 s

WebApplication.CreateBuilder loads every environment variable after the JSON files and user secrets, turning __ into the : separator, so ConnectionStrings__Adoptions overrides ConnectionStrings:Adoptions. ASPNETCORE_ and DOTNET_ variables are also loaded with the prefix stripped, but at the bottom of the chain.

open as a page

In ASP.NET Core, what do IConfiguration's indexer, GetSection, GetValue<T> and GetConnectionString return when a key is missing or cannot be converted?

level: middleimportance: should knowfreq 52%

basics

~20 s

The indexer and GetConnectionString return null for a missing key; GetSection returns an empty section, never null; GetValue<T> returns default(T) or the supplied default, and throws InvalidOperationException when the string cannot be converted to T.

open as a page

In ASP.NET Core, what sources does WebApplication.CreateBuilder load and in which order, and why might production ignore a value set in appsettings.Production.json?

level: seniorimportance: should knowfreq 58%

basics

~20 s

Later sources win: ASPNETCORE_ and DOTNET_ variables, appsettings.json, appsettings.{Environment}.json, {ApplicationName}.settings files, user secrets in Development, all environment variables, then command-line arguments. Production usually ignores a file value because a variable or argument overrides it, or the file never loads.

open as a page

In ASP.NET Core, what does reloadOnChange do for the appsettings files, which sources never reload, and how does code observe a change?

level: seniorimportance: should knowfreq 42%

basics

~20 s

With reloadOnChange, which the default builder turns on for every JSON file, a file watcher re-reads the file after a save and fires the configuration's reload token. Environment variables and command-line arguments are read once at startup and never reload.

open as a page

In ASP.NET Core, how do you build a custom configuration provider that loads feature switches from a database, and where does builder.Configuration.Add place it?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Write an IConfigurationSource whose Build returns a class derived from ConfigurationProvider, override Load to fill Data with colon keys, and call OnReload after a refresh. Adding it after CreateBuilder appends it last, above environment variables and arguments.

open as a page