App Settings and Configuration
On your laptop ReadingRoom uses a local SQLite file and lets members borrow five books. In production it talks to a real database and allows three. The code must be the same in both places; only the settings differ. ASP.NET Core's configuration system is how one build behaves correctly everywhere.
The rule
Settings stack in layers; the last layer to set a key wins.
WebApplication.CreateBuilder reads these sources, in this order:
appsettings.jsonappsettings.{Environment}.json— e.g.appsettings.Development.json- User secrets — only when the environment is Development
- Environment variables
- Command-line arguments
The environment name comes from the ASPNETCORE_ENVIRONMENT variable (Development, Staging or Production; Production if unset).
{
"ConnectionStrings": { "Library": "Data Source=library.db" },
"Loans": { "MaxPerMember": 5, "LengthDays": 14 }
}Keys are paths joined by colons: Loans:MaxPerMember. Environment variables cannot contain colons on every system, so they use a double underscore: Loans__MaxPerMember=3.
Rather than reading strings by key everywhere, bind a section to a class — the options pattern:
public class LoanOptions
{
public int MaxPerMember { get; set; }
public int LengthDays { get; set; }
}
builder.Services.Configure<LoanOptions>(builder.Configuration.GetSection("Loans"));
public class LoanService(IOptions<LoanOptions> options)
{
private readonly int _max = options.Value.MaxPerMember;
}Secrets never go in committed JSON. During development, dotnet user-secrets set "ConnectionStrings:Library" "..." stores them outside the project folder; in production, use environment variables or a secret store.
The shortcut
To predict a value, start at the bottom of the list and go up: the first source that sets the key is the answer.
Command line?
The app was started with no arguments. Keep going up.
The trap: committing a real connection string with a password to appsettings.json. Git remembers it even after you delete it.
Drills
Answer fast — trust the rule.
appsettings.json says 5 and the command line passes --Loans:MaxPerMember=7. Which value is used?
How is Loans:MaxPerMember written as an environment variable?
When are user secrets loaded by default?
Which line binds the Loans section to LoanOptions for injection?
Remember
- Settings stack in layers; the last layer to set a key wins.
- JSON → environment JSON → user secrets → environment variables → command line.
- Bind sections to classes with the options pattern; keep secrets out of Git.
