What are the different ways to manage application configuration?
4 minintermediateASP.NET-Coreconfigurationoptions
Quick Answer
Configuration comes from layered providers merged in order: `appsettings.json`, environment-specific `appsettings.{Environment}.json`, environment variables, command-line args, user secrets (dev), and cloud stores like Azure Key Vault. Values are read via `IConfiguration` or strongly-typed with the Options pattern (`IOptions<T>`). Later providers override earlier ones, enabling per-environment overrides without code changes.
Detailed Answer
ASP.NET Core provides multiple ways to manage configuration:
1. appsettings.json (Most Common)
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=MyDb;Trusted_Connection=true;"
},
"AppSettings": {
"ApplicationName": "MyApp",
"MaxFileSize": 10485760
}
}
2. Environment-Specific Configuration
appsettings.json (base configuration)
appsettings.Development.json (development overrides)
appsettings.Production.json (production overrides)
3. User Secrets (Development Only)
dotnet user-secrets init
dotnet user-secrets set "ApiKey" "secret-key-value"
4. Environment Variables
// Access in code
var apiKey = builder.Configuration["ApiKey"];
// Set in launchSettings.json
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ApiKey": "dev-key"
}
5. Command Line Arguments
dotnet run --ApiKey="command-line-key"
6. Azure Key Vault
builder.Configuration.AddAzureKeyVault(
new Uri("https://myvault.vault.azure.net/"),
new DefaultAzureCredential());
7. Options Pattern (Strongly Typed)
// Settings class
public class AppSettings
{
public string ApplicationName { get; set; }
public int MaxFileSize { get; set; }
}
// Register
builder.Services.Configure(
builder.Configuration.GetSection("AppSettings"));
// Use in controller
public class HomeController : Controller
{
private readonly AppSettings _settings;
public HomeController(IOptions settings)
{
_settings = settings.Value;
}
}
Configuration Priority (Highest to Lowest):
- Command-line arguments
- Environment variables
- User secrets
- appsettings.{Environment}.json
- appsettings.json