📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does configuration work in ASP.NET Core? Explain the default configuration providers and the order they load in (appsettings.json, appsettings.{Environment}.json, user secrets, environment variables, command line), why the last one wins, and how hierarchical keys work with : and __.

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.

Beginner Theory Beginner appsettings aspnet-core configuration environment-variables iconfiguration

🎯 Key points

  • IConfiguration is one flattened, case-insensitive key-value view merged from an ordered list of providers
  • CreateBuilder order: appsettings.json, appsettings.{Environment}.json, user secrets (Development only), environment variables, command-line args
  • When two providers set the same key, the provider added last wins; nothing is merged inside a value
  • Hierarchy is flattened with a colon: Logging:LogLevel:Default; arrays use indexes such as AllowedHosts:0
  • Environment variables use a double underscore (Logging__LogLevel__Default) because : is not valid in Linux variable names
  • appsettings files are loaded with reloadOnChange: true; environment variables and command-line args are read once at start-up
  • Read with GetValue<T>, GetSection, GetConnectionString or, better, bind to options classes

⏱ 30-second answer

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.

  • Hierarchy is flattened with :, e.g. ConnectionStrings:Default.
  • Environment variables use __ 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 IConfiguration stacks 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, then appsettings.{Environment}.json such as appsettings.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 becomes Logging:LogLevel:Default. Environment variables can't contain a colon on Linux, so I write Logging__LogLevel__Default with 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 IConfiguration with 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."


The default provider stack

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.

Key syntax

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

Reading values

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate knows where a configuration value comes from and how overrides work.

Green flags

  • Lists the default providers in order and states "last one wins".
  • Knows : for hierarchy and __ for environment variables.
  • Mentions user secrets are Development-only and secrets don't belong in appsettings.
  • Prefers binding to options over magic strings.

Red flags

  • Thinks appsettings.json always has the final say.
  • Believes environment variables reload while the app runs.
  • Puts production secrets in the JSON file.

📚 Learn in depth

1. Providers flatten everything to strings

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.

2. The root asks providers in reverse

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.

3. Sections are views, not copies

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.

4. Environment variable mapping

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.

5. Reloading

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.

Try it yourself

  1. Create a new web app, add "Greeting": "from json" to appsettings.json and map / to return config["Greeting"].
  2. Run with Greeting=from-env dotnet run, then dotnet run --Greeting=from-cli, and watch which value wins.
  3. Add an array with three items in JSON and set only Items__0 as an environment variable; print GetSection("Items").Get<string[]>().
  4. Print ((IConfigurationRoot)builder.Configuration).GetDebugView() to see every key and the provider that supplied it.
  5. Edit appsettings.json while the app runs and confirm the next request sees the new value.

💻 Code

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

⚠ Common mistakes

  • Mistake: Using : 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.
  • Mistake: Expecting arrays or objects to be replaced as a whole. Why it is wrong: Each flattened key (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.
  • Mistake: Adding a JSON file after 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.
  • Mistake: Putting secrets in 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.
  • Mistake: Mixing casing conventions (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.
  • Mistake: Setting overrides as environment variables in the portal or pipeline with no record of why. Why it is wrong: Six months later nobody knows which of the 40 variables still matter, and a new environment misses one. Instead: Keep environment settings in infrastructure as code (Bicep, Terraform, Helm values), document each override, and validate required values at start-up.
  • Mistake: Reading 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.
  • Mistake: Expecting an environment variable change to apply to a running app. Why it is wrong: Environment variables are read once at start-up. Instead: Restart, or use a reloadable source such as a file or Azure App Configuration.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions CreateBuilder setting up the defaults. Why: Checks what else the Generic Host and WebApplicationBuilder wire up besides configuration.
    How to answer

    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.

  2. When: Candidate mentions ASPNETCORE_ENVIRONMENT being set to Development locally. Why: Checks whether they know launchSettings.json sets environment variables only for local runs.
    How to answer

    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.

↩ Usually asked after

More in Configuration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me