Configuration & Options
Real apps need settings that change between machines: connection strings, API keys, feature flags, page sizes. ASP.NET Core reads them from several configuration providers and merges everything into one key/value view exposed as IConfiguration (builder.Configuration).
appsettings.json
A new project contains appsettings.json and appsettings.Development.json. Values are nested JSON objects:
{
"Logging": {
"LogLevel": { "Default": "Information" }
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Default": "Data Source=todos.db"
},
"Todo": {
"PageSize": 20,
"AllowDelete": false
}
}Internally, nesting is flattened into keys joined with a colon: Todo:PageSize, ConnectionStrings:Default. You can read single values directly:
var builder = WebApplication.CreateBuilder(args);
int pageSize = builder.Configuration.GetValue<int>("Todo:PageSize");
string? cs = builder.Configuration.GetConnectionString("Default"); // reads ConnectionStrings:DefaultProvider order: later wins
WebApplication.CreateBuilder registers these sources, in this order. When two sources define the same key, the one added later overrides the earlier one:
| # | Source | Example |
|---|---|---|
| 1 | appsettings.json |
"Todo": { "PageSize": 20 } |
| 2 | appsettings.{Environment}.json |
appsettings.Production.json |
| 3 | User secrets (Development only) | dotnet user-secrets set "Todo:ApiKey" "abc" |
| 4 | Environment variables | Todo__PageSize=50 |
| 5 | Command-line arguments | --Todo:PageSize=100 |
Environment variables can't contain : on every OS, so a double underscore __ stands for the colon. The following simulated session overrides the same key three ways:
# started with: dotnet run --urls http://localhost:5000
$ curl -s localhost:5000/settings
# restarted with: Todo__PageSize=50 dotnet run --urls http://localhost:5000
$ curl -s localhost:5000/settings
# restarted with: dotnet run --urls http://localhost:5000 --Todo:PageSize=100
$ curl -s localhost:5000/settings{"pageSize":20,"allowDelete":false}
{"pageSize":50,"allowDelete":false}
{"pageSize":100,"allowDelete":false}
Here is the same "last one wins" merge written in plain C#. Each layer is a dictionary of flattened keys, and we then bind the Todo section to a class:
using System;
using System.Collections.Generic;
using System.Linq;
var layers = new List<(string Name, Dictionary<string, string> Values)>
{
("appsettings.json", new() { ["Todo:PageSize"] = "20", ["Todo:AllowDelete"] = "false", ["Todo:Title"] = "My Todos" }),
("appsettings.Production.json", new() { ["Todo:AllowDelete"] = "true" }),
("environment", new() { ["Todo:PageSize"] = "50" }), // from Todo__PageSize=50
("command line", new() { ["Todo:Title"] = "Team Todos" }),
};
var merged = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var source = new Dictionary<string, string>();
foreach (var (name, values) in layers)
foreach (var (key, value) in values)
{
merged[key] = value;
source[key] = name;
}
foreach (var key in merged.Keys.OrderBy(k => k))
Console.WriteLine(quot;{key,-16} = {merged[key],-10} (from {source[key]})");
var options = new TodoOptions
{
PageSize = int.Parse(merged["Todo:PageSize"]),
AllowDelete = bool.Parse(merged["Todo:AllowDelete"]),
Title = merged["Todo:Title"],
};
Console.WriteLine(options);
record TodoOptions
{
public int PageSize { get; init; }
public bool AllowDelete { get; init; }
public string Title { get; init; } = "";
}Todo:AllowDelete = true (from appsettings.Production.json)
Todo:PageSize = 50 (from environment)
Todo:Title = Team Todos (from command line)
TodoOptions { PageSize = 50, AllowDelete = True, Title = Team Todos }
Note: Keys are case-insensitive:
todo:pagesizeandTodo:PageSizeare the same setting.
User secrets
Never commit passwords or API keys. In development, store them outside the project folder with the Secret Manager:
$ dotnet user-secrets init
$ dotnet user-secrets set "Mail:ApiKey" "dev-key-123"
$ dotnet user-secrets listSet UserSecretsId to 'c1f7d3a2-5b8e-4f61-9d2a-7e0b4c6a8f13' for MSBuild project '/home/dev/TodoApi/TodoApi.csproj'.
Successfully saved Mail:ApiKey to the secret store.
Mail:ApiKey = dev-key-123
The secrets live in a JSON file in your user profile and are only loaded when the environment is Development. In production, use environment variables or a vault such as Azure Key Vault.
The options pattern
Reading strings by key everywhere is fragile. The options pattern binds a configuration section to a strongly-typed class once and injects it:
public class TodoOptions
{
public const string Section = "Todo";
[Range(1, 100)]
public int PageSize { get; set; } = 10;
public bool AllowDelete { get; set; }
}
builder.Services.AddOptions<TodoOptions>()
.Bind(builder.Configuration.GetSection(TodoOptions.Section))
.ValidateDataAnnotations() // check [Range], [Required], ...
.ValidateOnStart(); // fail at startup, not on first use
app.MapGet("/settings", (IOptions<TodoOptions> options) => options.Value);Three interfaces give you the options, with different refresh behaviour:
| Interface | Lifetime | Sees changes to appsettings.json while running? |
|---|---|---|
IOptions<T> |
Singleton | No — read once |
IOptionsSnapshot<T> |
Scoped | Yes, re-read per request |
IOptionsMonitor<T> |
Singleton | Yes, CurrentValue + OnChange callback |
ValidateDataAnnotations uses the same attributes as model validation. Here is what happens to an invalid value, run with the System.ComponentModel.DataAnnotations validator directly:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
var options = new TodoOptions { PageSize = 500, ContactEmail = "" };
var errors = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(options, new ValidationContext(options), errors, validateAllProperties: true);
Console.WriteLine(valid ? "Options OK" : "Options validation failed:");
foreach (var e in errors)
Console.WriteLine(quot; - {e.ErrorMessage}");
class TodoOptions
{
[Range(1, 100)]
public int PageSize { get; set; } = 10;
[Required]
public string ContactEmail { get; set; } = "";
}Options validation failed:
- The field PageSize must be between 1 and 100.
- The ContactEmail field is required.
With ValidateOnStart(), such errors stop the app with an OptionsValidationException before it accepts any traffic — far better than discovering the problem on the first request.
Tip: Keep secrets out of
appsettings.json, keep non-secret defaults in it, and let the environment override what differs per deployment.
Test yourself
Which environment variable sets the configuration key Todo:PageSize?
- Todo.PageSize
- TODO_PAGESIZE
- Todo:PageSize only
- Todo__PageSize
appsettings.json sets PageSize to 20 and a command-line argument sets it to 100. Which value does the app see?
- 20
- 100
- The app fails to start
- Whichever file was edited last
Which options interface picks up a changed appsettings.json value on the next request?
- IOptions<T>
- IOptionsSnapshot<T>
- IConfigurationSection
- OptionsBuilder<T>