
Tired of hardcoding settings? .NET Core's flexible configuration system lets you manage app settings like a pro! Here's everything you need to know:
✔ appsettings.json - Primary JSON config
✔ Environment variables - For deployment-specific settings
✔ Command-line arguments - Runtime overrides
✔ User secrets - Secure local development
✔ Azure Key Vault - Cloud secrets management
var builder = WebApplication.CreateBuilder(args);
// Access configuration
var config = builder.Configuration;
// Read values
var apiKey = config["ApiSettings:Key"];
var timeout = config.GetValue<int>("TimeoutSeconds");
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"ConnectionStrings": {
"Default": "Server=localhost;Database=MyApp;"
},
"ApiSettings": {
"Url": "https://api.example.com",
"Key": "secret123",
"Timeout": 30
}
}
Access nested values:
var apiUrl = config["ApiSettings:Url"];
var dbConn = config.GetConnectionString("Default");
FileWhen Usedappsettings.Development.jsonLocal devappsettings.Production.jsonLive env
.NET Core automatically loads the right file based on ASPNETCORE_ENVIRONMENT!
For sensitive data (API keys, passwords):
dotnet user-secrets init dotnet user-secrets set "ApiSettings:Key" "super-secret"
Access like normal config:
var secretKey = config["ApiSettings:Key"];
Powerful for containers/cloud:
export ApiSettings__Key=prod-secret-key
Note double underscore for nesting)
Access in code:
var envKey = config["ApiSettings:Key"];
1. Strongly-typed config:
builder.Services.Configure<ApiSettings>(
builder.Configuration.GetSection("ApiSettings"));
2. Validation with DataAnnotations:
public class ApiSettings
{
[Required]
public string Url { get; set; }
[Range(1, 60)]
public int Timeout { get; set; }
}
❌ Hardcoding sensitive data
❌ Not using environment-specific configs
❌ Forgetting to call AddUserSecrets() in Development
✔ Unified access to multiple sources
✔ Environment-aware loading
✔ Hierarchical structure
✔ Runtime reload with reloadOnChange: true
Try it today! Replace just ONE hardcoded value with configuration.
#DotNetCore #Configuration #AppSettings #CSharp #BestPractices