Lesson 14 / 26

Configuration and Environments

Read settings from appsettings.json, environment variables and user secrets.

Layers of settings

Configuration is layered: appsettings.json, then appsettings.{Environment}.json, then user secrets (in Development), then environment variables, then command-line arguments. Later sources override earlier ones.

Reading and setting values

Nested keys use : in code and __ in environment variable names. dotnet user-secrets keeps development secrets out of the repo.

// appsettings.json: { "Shop": { "PageSize": 20 } }
var pageSize = builder.Configuration.GetValue<int>("Shop:PageSize");

// Shell:
//   dotnet user-secrets init
//   dotnet user-secrets set "ConnectionStrings:Default" "Server=...;Password=..."
//   export Shop__PageSize=50   # overrides appsettings.json

Never commit secrets

Passwords, API keys and signing keys do not belong in appsettings.json. Use user secrets locally and environment variables or a secret manager in production.

Quick check: Which source wins when the same key is set in appsettings.json and an environment variable?

  • appsettings.json
  • The first one the app reads
  • Neither; it throws an error
  • The environment variable
Answer

The environment variable — Environment variables are added after the JSON files, so they override them.