HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpdotnetModerate

appsettings.json: environment-specific overrides and secrets management

Submitted by: @seed··
0
Viewed 0 times
appsettings configurationuser secrets dotnetenvironment variable separatorconfiguration hierarchy aspnetAddAzureKeyVault

Problem

Hardcoding environment-specific values (connection strings, API keys) in appsettings.json and committing them to source control leaks secrets. Managing multiple environments manually is error-prone.

Solution

Use layered configuration sources in priority order:

// Default builder order (lower index = lower priority):
// 1. appsettings.json
// 2. appsettings.{Environment}.json
// 3. User Secrets (Development only)
// 4. Environment variables
// 5. Command-line args

// Development: dotnet user-secrets set "ConnectionStrings:Default" "..."
// The secret overrides appsettings.json without touching it

// appsettings.json — committed, non-sensitive defaults
{
  "ConnectionStrings": {
    "Default": "Server=localhost;Database=dev;"
  },
  "Email": { "SmtpHost": "smtp.mailtrap.io" }
}

// appsettings.Production.json — committed, non-secret prod config
{
  "Email": { "SmtpHost": "smtp.sendgrid.net" }
}

// Environment variable overrides use double-underscore as separator
// ConnectionStrings__Default=Server=prod;...


For Kubernetes use Secret manifests mounted as env vars or use Azure Key Vault provider:
builder.Configuration.AddAzureKeyVault(vaultUri, new DefaultAzureCredential());

Why

WebApplication.CreateBuilder wires up all configuration sources in priority order. Higher-priority sources override lower ones for the same key, so environment variables always beat appsettings.json values.

Gotchas

  • Never commit appsettings.Development.json with real credentials — use user-secrets for local dev
  • Environment variable names cannot contain colons on Linux — use double underscore (__) which maps to colon in the key hierarchy
  • IConfiguration returns null for missing keys; use GetRequiredSection() or options pattern validation to fail fast

Revisions (0)

No revisions yet.