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.