The Analogy: The Control Panel and the Locked Drawer
A piece of industrial machinery has a control panel: labelled dials for the settings that change between sites, jobs and shifts. The machine's behaviour is welded in; the dials are the parts the operator is allowed to turn. A well-designed panel has exactly the dials that need turning and no more, each one labelled, each one with a sensible factory position.
The panel also has a locked drawer. The site's access codes go in there — not printed on the front, not written on a sticky note, not shipped with the machine from the factory. Anyone can read the dials; only the operator with a key can read the drawer. A machine that has its access code silk-screened onto the panel is not badly configured, it is unsafe.
.NET configuration is that panel. appsettings.json is the factory positions, an environment-specific file adjusts them per site, environment variables adjust them per container, and command-line arguments adjust them for one run — with later sources overriding earlier ones, so the most specific instruction wins. Secrets live in the locked drawer: user secrets while developing, environment variables or a secret manager in production, and never in a file you commit.
The last piece is the difference between reading a dial and trusting it. config["Smtp:Port"] hands you a string that may be missing, misspelled or unparseable, and you find out at the moment you use it. The options pattern turns the whole panel into a class with typed properties and validation rules that run at startup, so a misconfigured deployment fails immediately and loudly instead of at three in the morning when the first email goes out.
Syntax or Core Structure
Configuration is built by stacking providers. Each provider contributes a flat dictionary of Key -> string pairs; nested structure is expressed with colons (Smtp:Port), and array elements with numeric segments (Smtp:Recipients:0). The two in-memory collections below stand in for appsettings.json and appsettings.Production.json so the example runs anywhere without extra files:
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
class SmtpOptions
{
public string Host { get; set; } = "";
public int Port { get; set; }
public bool UseTls { get; set; }
public string[] Recipients { get; set; } = Array.Empty<string>();
}
class Program
{
static void Main()
{
// Stands in for appsettings.json - the factory positions.
var baseSettings = new Dictionary<string, string?>
{
["Smtp:Host"] = "localhost",
["Smtp:Port"] = "25",
["Smtp:UseTls"] = "false",
["Smtp:Recipients:0"] = "ops@example.com",
["Smtp:Recipients:1"] = "audit@example.com",
["Feature:NewCheckout"] = "false"
};
// Stands in for appsettings.Production.json - the site adjustments.
var overrides = new Dictionary<string, string?>
{
["Smtp:Host"] = "smtp.example.com",
["Smtp:Port"] = "587",
["Smtp:UseTls"] = "true",
["Feature:NewCheckout"] = "true"
};
IConfiguration config = new ConfigurationBuilder()
.AddInMemoryCollection(baseSettings)
.AddInMemoryCollection(overrides) // added last, so it wins
.Build();
SmtpOptions smtp = config.GetSection("Smtp").Get<SmtpOptions>()!;
Console.WriteLine("host: " + smtp.Host);
Console.WriteLine("port: " + smtp.Port);
Console.WriteLine("tls: " + smtp.UseTls);
Console.WriteLine("recipients: " + string.Join(", ", smtp.Recipients));
Console.WriteLine("flag: " + config.GetValue<bool>("Feature:NewCheckout"));
Console.WriteLine("timeout: " + config.GetValue("Smtp:Timeout", 30));
}
}
Output:
host: smtp.example.com
port: 587
tls: True
recipients: ops@example.com, audit@example.com
flag: True
timeout: 30
Every line here is a rule in action. Host, Port, UseTls and the feature flag all came from the second collection because it was added last. Recipients survived untouched because the override said nothing about it — providers merge key by key, they do not replace whole sections. Port and UseTls arrived as the strings "587" and "true" and were converted by the binder, which is why UseTls prints True rather than the JSON-style true. And Smtp:Timeout does not exist in either collection, so GetValue returned the supplied fallback of 30 rather than throwing.
That last point is the one that bites people. A key that is absent is not an error by default — config["Nope:Missing"] is simply null, and GetValue<int>("Nope:Missing") is 0. If a setting is mandatory you have to say so, either with GetValue plus an explicit fallback, with config.GetSection("Smtp").Exists(), or — much better — with validated options, which the Real World Example builds.
Technical Depth: Providers, Precedence and the Options Pattern
The default provider stack
When you call Host.CreateApplicationBuilder(args) or WebApplication.CreateBuilder(args), .NET registers a stack of providers for you. Order matters: later wins.
| Order | Provider | Typical use |
|---|---|---|
| 1 | appsettings.json | Committed defaults, safe to read |
| 2 | appsettings.{Environment}.json | Per-environment adjustments |
| 3 | User secrets (Development only) | Local dev keys, stored outside the repo |
| 4 | Environment variables | Container and CI configuration |
| 5 | Command-line arguments | One-off overrides for a single run |
The environment name comes from ASPNETCORE_ENVIRONMENT (web) or DOTNET_ENVIRONMENT (generic host), defaulting to Production when unset. That default is deliberate: an unlabelled machine is treated as the strictest case, not the loosest.
Writing hierarchical keys in each provider
The same setting looks different depending on where it lives, because not every medium allows a colon:
| Source | How you write Smtp:Port |
|---|---|
| JSON | Nested object: "Smtp": { "Port": 587 } |
| Environment variable | Smtp__Port=587 (double underscore) |
| Command line | --Smtp:Port=587 or --Smtp:Port 587 |
| User secrets | dotnet user-secrets set "Smtp:Port" "587" |
| In-memory | ["Smtp:Port"] = "587" |
The double underscore exists because colons are illegal in environment variable names on some platforms. Both Smtp__Port and Smtp:Port work on Windows; only the underscore form is portable, so use it everywhere. Keys are also case-insensitive, so smtp:port finds the same value — but values are not, and neither are file names on Linux, which is why appsettings.Production.json with a lowercase p silently does nothing on a Linux container.
IConfiguration versus the options pattern
Injecting IConfiguration everywhere works and is almost always the wrong choice. It hands every class a stringly-typed dictionary of the entire application's settings, with no type safety, no validation and no way to see from a constructor what a class actually depends on. The options pattern narrows that to a class per concern:
| Interface | Lifetime | Reloads? | Use it when |
|---|---|---|---|
IOptions<T> | Singleton | No | Settings fixed for the process lifetime |
IOptionsSnapshot<T> | Scoped | Per request/scope | A request should see a consistent set |
IOptionsMonitor<T> | Singleton | Yes, with OnChange | Long-lived services that must react to edits |
IOptions<T> is bound once and cached forever, so a singleton holding options.Value never sees a file edit. IOptionsMonitor<T> re-reads on change and exposes CurrentValue plus an OnChange callback; you must read CurrentValue at the point of use rather than caching it in a field, or you have re-implemented IOptions by accident.
Binding rules worth knowing
Get<T>() and Bind(instance) use public settable properties, matched by name, case-insensitively. Constructor parameters are supported for records and immutable types in modern .NET, but plain classes need a public parameterless constructor. Keys with no matching property are ignored silently unless you opt in with options.ErrorOnUnknownConfiguration = true, which turns a typo like TimoutSeconds from a shrug into a startup failure. Collections bind from numeric child keys, and dictionaries bind from named child keys.
Secrets: the locked drawer
Configuration is where credentials leak, so treat these as rules rather than advice:
appsettings.jsonis committed. Never put a password, key or token in it — put the name of the setting there with an empty or absent value, and supply the value elsewhere.dotnet user-secrets set "Payments:ApiKey" "<value>"stores a development value in your user profile, outside the repository, keyed by theUserSecretsIdin the.csproj. It is loaded only in the Development environment and is not encrypted — it is protection againstgit commit, not against someone with your laptop.- In production, supply secrets as environment variables injected by the platform, or from a managed secret store such as Azure Key Vault, AWS Secrets Manager or HashiCorp Vault.
- Never log a configuration value that might be a secret. Log the key name, or a masked form that keeps at most the last few characters for support calls.
- Connection strings belong in the
ConnectionStringssection and are read withconfig.GetConnectionString("Primary"), which is just sugar forconfig["ConnectionStrings:Primary"]. They usually contain a password, so they follow every rule above.
Reloading
File providers are registered with reloadOnChange: true by default in the host builders, so editing appsettings.json on a running process updates IConfiguration and anything reading through IOptionsMonitor<T> or IOptionsSnapshot<T>. This is genuinely useful for log levels and feature flags. It is not a substitute for a deployment: changes reached this way are invisible to source control and vanish on the next container restart.
Real World Example: Failing Fast on a Bad Deployment
A payment integration has four settings. Three are safe to commit; one is a key that must never appear in the repository. The team has been bitten twice by a deployment that started cleanly, served traffic for twenty minutes, then failed on the first checkout because the key was missing from the container. The fix is to make the process refuse to start.
appsettings.json — committed, contains no secret:
{
"Payments": {
"ApiBaseUrl": "https://payments.example.com/v1",
"TimeoutSeconds": 20,
"RetryCount": 2
}
}
The key is supplied by the platform as an environment variable, using the double-underscore form:
export Payments__ApiKey="sk_live_0000000000000000abcd"
dotnet run
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
sealed class PaymentOptions
{
public const string Section = "Payments";
[Required, Url]
public string ApiBaseUrl { get; set; } = "";
// Never present in appsettings.json - supplied by env var or secret store.
[Required, MinLength(20)]
public string ApiKey { get; set; } = "";
[Range(1, 120)]
public int TimeoutSeconds { get; set; } = 30;
[Range(0, 5)]
public int RetryCount { get; set; } = 3;
}
sealed class PaymentClient
{
private readonly PaymentOptions options;
// The constructor advertises exactly what this class needs.
public PaymentClient(IOptions<PaymentOptions> options) => this.options = options.Value;
public void Describe()
{
Console.WriteLine("endpoint: " + options.ApiBaseUrl);
Console.WriteLine("timeout: " + options.TimeoutSeconds + "s, retries: " + options.RetryCount);
Console.WriteLine("key: " + Mask(options.ApiKey));
}
// Support needs to identify a key without anyone reading it aloud.
private static string Mask(string value) =>
value.Length <= 4 ? "****" : new string('*', value.Length - 4) + value[^4..];
}
class Program
{
static void Main(string[] args)
{
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services
.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection(PaymentOptions.Section))
.ValidateDataAnnotations()
.Validate(o => o.RetryCount == 0 || o.TimeoutSeconds >= 5,
"TimeoutSeconds must be at least 5 when retries are enabled.")
.ValidateOnStart();
builder.Services.AddSingleton<PaymentClient>();
using IHost host = builder.Build();
host.Start(); // ValidateOnStart runs here - before any traffic arrives
host.Services.GetRequiredService<PaymentClient>().Describe();
}
}
Output: with Payments__ApiKey set
endpoint: https://payments.example.com/v1
timeout: 20s, retries: 2
key: ************************abcd
Output: with the variable unset (abridged - the exact exception wording varies by .NET version)
Unhandled exception. Microsoft.Extensions.Options.OptionsValidationException:
DataAnnotation validation failed for 'PaymentOptions' members: 'ApiKey' with the
error: 'The ApiKey field is required.'.
The second run is the whole point of the exercise. ValidateOnStart() moves validation from "the first time somebody resolves IOptions<PaymentOptions>" to "before the host finishes starting", which in a real deployment means the container exits immediately and the orchestrator refuses to route traffic to it. The previous version of this service started happily, passed its health check, and failed twenty minutes later — a far more expensive failure than a crash at boot, because by then the bad build was live and the good one was gone.
The data annotations do real work here beyond presence checks. [Url] catches the copy-paste that leaves off the scheme, [Range(1, 120)] catches a TimeoutSeconds of 0 that would otherwise mean "wait forever", and [MinLength(20)] catches the case where the environment variable exists but was set to a placeholder or truncated by a broken shell quote. The extra .Validate(...) lambda covers the rule annotations cannot express — a relationship between two settings — and gets its own message so the log says which rule failed rather than just "invalid".
Notice that PaymentClient never touches IConfiguration. It asks for IOptions<PaymentOptions> and receives an object that is already validated, so the class contains no parsing, no null checks and no defaults. Anyone reading the constructor learns exactly which settings this class depends on, which is information you simply cannot get from a class that injects IConfiguration and indexes into it. That is also what makes the class testable: a unit test constructs Options.Create(new PaymentOptions { ... }) and never goes near a JSON file.
Finally, the masking. Support engineers legitimately need to know which key a service is using — keys get rotated, and two environments get crossed. Printing the last four characters answers that question; printing the whole key writes a live credential into a log aggregator that a much wider group of people can read. The key name is safe to log in full; the value never is.
Common Mistakes
- Committing a secret to
appsettings.json. It is in the repository forever, visible to everyone with read access and to every fork and clone. Once it happens the key must be rotated, not just deleted from the file — removing the line does not remove it from history. - Assuming a missing key throws.
config["Smtp:Host"]returnsnullandGetValue<int>("Smtp:Port")returns0when the key is absent. The failure surfaces later as a null reference or a connection to port zero, far from the real cause. - Using a single underscore in an environment variable.
Smtp_Portcreates a top-level key literally namedSmtp_Port; onlySmtp__Portmaps to theSmtp:Porthierarchy. The application reads its default and nobody notices until the value matters. - Lowercasing the environment file name.
appsettings.production.jsonis found on Windows and ignored on Linux, so the same build behaves differently in CI and in the container. The file name must matchASPNETCORE_ENVIRONMENTexactly, including case. - Expecting a section to be replaced wholesale. Adding
"Smtp": { "Host": "..." }to the environment-specific file overridesHostonly; every other key in the base file survives. That is usually what you want, but it means you cannot "clear" a base setting by omitting it - you have to set it to an empty value. - Caching
IOptionsMonitor<T>.CurrentValuein a field. Reading it once in the constructor freezes the value, which is exactly the behaviour ofIOptions<T>with extra ceremony. ReadCurrentValueat the point of use, or useIOptions<T>and be honest about it. - Injecting
IConfigurationinto business classes. It hides dependencies, spreads magic strings across the codebase, defeats compile-time checking, and forces tests to build a configuration root. Bind once at startup and inject typed options instead. - Logging configuration at startup by dumping every key.
config.AsEnumerable()is a wonderful debugging tool and a terrible logging statement: it writes connection strings and API keys into whatever collects your logs.
Best Practices
- Keep committed files free of secrets by construction: the setting's name lives in
appsettings.json, the value comes from user secrets locally and from the platform or a secret store in production. - Bind each cohesive group of settings to its own options class with a
public const string Sectionnaming its section, so the section name is written once. - Always chain
ValidateDataAnnotations()andValidateOnStart(). A misconfigured process should fail to start, not fail on its first real request. - Use
.Validate(predicate, message)for cross-field rules, giving each one a message that names the setting and the constraint. - Prefer
Payments__ApiKeydouble-underscore form for all environment variables so the same value works unchanged on Windows, Linux and macOS. - Read connection strings through
GetConnectionString(name)and treat them as secrets, because they normally embed credentials. - Choose the options interface deliberately:
IOptions<T>for fixed settings,IOptionsSnapshot<T>for per-request consistency,IOptionsMonitor<T>only where the service genuinely must react to changes. - Mask any value that could be a credential before it reaches a log, keeping at most the last few characters so support can identify which key is in use.
Practice Exercises
- Prove the precedence order. Create a console app with an
appsettings.jsoncontaining"Report": { "Format": "csv", "Rows": 100 }, anappsettings.Development.jsonsettingFormatto"json", and then run it three times: plain, withReport__Rows=250in the environment, and with--Report:Rows=500on the command line. Print both values each time and write down which provider won and why. - Convert a stringly-typed service. Take a class that injects
IConfigurationand reads four keys withconfig["..."], and replace it with aReportOptionsclass bound at startup and injected asIOptions<ReportOptions>. Add[Required]and[Range]attributes plusValidateOnStart(), then deliberately break one setting and confirm the process refuses to start. - Build a masked configuration dump. Write a diagnostic method that walks
config.AsEnumerable(), sorts the keys ordinally, and prints each one - but replaces the value with***whenever the key containsKey,Secret,Password,TokenorConnectionStrings(case-insensitively). Verify that a fake connection string in your own settings comes out redacted. - Watch a live reload. Add a
Loggingsection with a custom"Threshold"value, injectIOptionsMonitor<AlertOptions>into a class that printsCurrentValue.Thresholdevery two seconds, then editappsettings.jsonwhile the program runs. Register anOnChangecallback that logs the old and new values, and confirm that an equivalent class holdingIOptions<AlertOptions>never sees the edit.