Configuration and the Options pattern
Settings like a payment gateway URL, a timeout and an API key must live outside the code and differ per environment. ASP.NET Core builds configuration from layered sources (appsettings, environment files, user-secrets, environment variables), and the Options pattern binds it to typed, validated classes.
40.1 Why is it used?
- The same build runs in Development, Staging and Production with different URLs, timeouts and keys.
- Secrets must never be committed to git; they come from user-secrets locally and environment variables or a vault on servers.
- Reading raw string keys fails silently: a typo returns null or 0 and you find out in production.
- Typed options with validation catch a bad config at startup (fail fast).
40.2 The bug: wrong key, no error
- IConfiguration is injected and read with string keys.
- The code says Payment:TimeoutSecond but appsettings has TimeoutSeconds: timeout is 0 and there is no error.
var builder = WebApplication.CreateBuilder(args);var app = builder.Build(); app.MapGet("/payment/settings", (IConfiguration config) =>{ var url = config["Payment:BaseUrl"]; var timeout = config.GetValue<int>( "Payment:TimeoutSecond"); return new { url, timeout };}); app.Run();$ curl -i localhost:5140/payment/settingsHTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{ "url": "https://sandbox.paygate.example", "timeout": 0 }- Step 1
1.Configuration is a flat key/value store of strings
- Step 2
2.GetValue<int>("Payment:TimeoutSecond") looks up a typo
- Step 3
3.Key missing: returns default 0, no exception
- Step 4
4.Endpoint happily returns timeout 0
- Step 5
5.Found only when every payment times out in production
Needed: typed + validated settings
40.3 appsettings.json and sections
- Settings are grouped in sections, e.g. Payment with BaseUrl and TimeoutSeconds.
- Configuration flattens nesting into keys joined by a colon: Payment:BaseUrl.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "Payment": { "BaseUrl": "https://api.paygate.example", "TimeoutSeconds": 30 }}40.4 Environments: appsettings.{Env}.json
- The environment name comes from ASPNETCORE_ENVIRONMENT; launchSettings sets Development for local runs.
- appsettings.Development.json loads after appsettings.json, so its BaseUrl (sandbox) overrides the base value.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "Payment": { "BaseUrl": "https://sandbox.paygate.example" }}$ dotnet runinfo: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5140info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development$ curl localhost:5140/payment/settings{ "url": "https://sandbox.paygate.example", "timeout": 0 }40.5 Configuration sources and order
| Order | Source | Notes |
|---|---|---|
| 1 | appsettings.json | Base values, committed to git |
| 2 | appsettings.{Environment}.json | Development, Production overrides |
| 3 | User secrets | Development only; plain JSON outside the project |
| 4 | Environment variables | Payment__ApiKey (double underscore = colon) |
| 5 | Command line | --Payment:TimeoutSeconds=5; loaded last |
- Step 1
1.appsettings.json: base values
- Step 2
2.appsettings.{Env}.json: per-environment overrides
- Step 3
3.User secrets: Development only
- Step 4
4.Environment variables
- Step 5
5.Command line arguments: loaded last
Loaded later = wins
40.6 Options pattern: a typed class
- PaymentOptions is a normal class; property names match the JSON keys and Section = "Payment".
- Data annotations describe valid values: [Required, Url] BaseUrl, [Required] ApiKey, [Range(1, 60)] TimeoutSeconds.
using System.ComponentModel.DataAnnotations; public class PaymentOptions{ public const string Section = "Payment"; [Required, Url] public string BaseUrl { get; set; } = ""; [Required] public string ApiKey { get; set; } = ""; [Range(1, 60)] public int TimeoutSeconds { get; set; }}40.7 Register, bind and validate on start
- AddOptions<PaymentOptions>() registers the options.
- BindConfiguration("Payment") fills the class from the Payment section.
- ValidateDataAnnotations() checks the attributes; ValidateOnStart() runs the check when the app starts.
- No ApiKey anywhere yet, so the app refuses to start with a clear error.
using Microsoft.Extensions.Options; var builder = WebApplication.CreateBuilder(args); builder.Services.AddOptions<PaymentOptions>() .BindConfiguration(PaymentOptions.Section) .ValidateDataAnnotations() .ValidateOnStart(); var app = builder.Build();$ dotnet runfail: Microsoft.Extensions.Hosting.Internal.Host[11] Hosting failed to start OptionsValidationException: DataAnnotation validation failed for 'PaymentOptions' members: 'ApiKey' with the error: 'The ApiKey field is required.'.40.8 Secrets: user-secrets in Development
- Secrets do not go in appsettings because that file is committed.
- dotnet user-secrets init adds a UserSecretsId to the project file.
- set stores the value in secrets.json in your user profile, outside the project folder; list shows it.
dotnet user-secrets initdotnet user-secrets set \ "Payment:ApiKey" "test_key_FAKE_0000"dotnet user-secrets list$ dotnet user-secrets set "Payment:ApiKey" \ "test_key_FAKE_0000"Successfully saved Payment:ApiKey to the secret store.$ dotnet user-secrets listPayment:ApiKey = test_key_FAKE_000040.9 IOptions in an endpoint
- Inject IOptions<PaymentOptions> and use .Value: typed, no string keys, no typos.
- Mask secrets: show only the first characters (ApiKey[..9] + "****"), never the full key in a response or log.
app.MapGet("/payment/settings", (IOptions<PaymentOptions> options) =>{ var o = options.Value; return new { o.BaseUrl, o.TimeoutSeconds, Key = o.ApiKey[..9] + "****" };});$ curl -i localhost:5140/payment/settingsHTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{ "baseUrl": "https://sandbox.paygate.example", "timeoutSeconds": 30, "key": "test_key_****" }40.10 Production: environment variables
- User-secrets are not loaded in Production; secrets come from environment variables (or Key Vault / a cloud secret manager).
- A double underscore replaces the colon: Payment__ApiKey, Payment__TimeoutSeconds, because not every OS allows a colon in variable names.
- Result: the production BaseUrl from appsettings.json and timeout 10 from the environment variable.
export ASPNETCORE_ENVIRONMENT=Productionexport Payment__ApiKey=test_key_FAKE_9999export Payment__TimeoutSeconds=10dotnet run --no-launch-profile \ --urls http://localhost:5140info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5140info: Microsoft.Hosting.Lifetime[0] Hosting environment: Production$ curl localhost:5140/payment/settings{ "baseUrl": "https://api.paygate.example", "timeoutSeconds": 10, "key": "test_key_****" }40.11 IOptions vs IOptionsSnapshot vs IOptionsMonitor
| Interface | Lifetime | Value | Reload |
|---|---|---|---|
| IOptions<T> | Singleton | Read once, kept until restart | No |
| IOptionsSnapshot<T> | Scoped | Fresh per request | Yes, next request |
| IOptionsMonitor<T> | Singleton | CurrentValue is always latest | Yes, immediately (OnChange too) |
- Checkpoint: all three return 30; TimeoutSeconds changed to 45 while running gives 30, 45, 45.
- Do not inject IOptionsSnapshot into a singleton: that is a captive dependency; use IOptionsMonitor there.
app.MapGet("/timeout/options", (IOptions<PaymentOptions> o) => o.Value.TimeoutSeconds);app.MapGet("/timeout/snapshot", (IOptionsSnapshot<PaymentOptions> o) => o.Value.TimeoutSeconds);app.MapGet("/timeout/monitor", (IOptionsMonitor<PaymentOptions> o) => o.CurrentValue.TimeoutSeconds);# appsettings.json: TimeoutSeconds 30 → 45$ curl localhost:5140/timeout/options30$ curl localhost:5140/timeout/snapshot45$ curl localhost:5140/timeout/monitor4540.12 Common mistakes
- Scattering IConfiguration string keys through the code instead of a typed options class.
- No ValidateOnStart: a wrong config is discovered at runtime, not startup.
- Committing secrets to appsettings.json: they stay in git history and are hard to remove.
- Myth: user-secrets are encrypted and safe for production. They are plain JSON outside the project and load only in Development.
{ "Payment": { "BaseUrl": "https://api.paygate.example", "ApiKey": "live_key_FAKE_DO_NOT_USE", "TimeoutSeconds": 30 }}{ "Payment": { "BaseUrl": "https://api.paygate.example", "TimeoutSeconds": 30 }}40.13 Interview tips
- Configuration is built from multiple providers; the one loaded later wins, so environment variables override the JSON files.
- Bind settings to a typed class with BindConfiguration and validate with ValidateDataAnnotations + ValidateOnStart.
- IOptions reads once; IOptionsSnapshot (scoped) and IOptionsMonitor (singleton, CurrentValue) pick up reloads.
- Secrets: user-secrets in development, environment variables / Key Vault in production, never in git.
- Env var naming: Section__Key, double underscore for the colon.