1. Configuration Providers
.NET Core supports many configuration sources.
- appsettings.json
- appsettings.{Environment}.json
- Environment variables
- Command-line arguments
- User Secrets
- Azure Key Vault
var builder = WebApplication.CreateBuilder(args);
builder.Configuration
.AddJsonFile("appsettings.json")
.AddJsonFile(
$"appsettings.{builder.Environment.EnvironmentName}.json",
optional: true
)
.AddEnvironmentVariables()
.AddCommandLine(args);
2. Strongly Typed Configuration
Map configuration to C# classes using the IOptions pattern.
// appsettings.json
{
"MySettings": {
"SiteTitle": "My App",
"MaxItems": 10
}
}
public class MySettings
{
public string SiteTitle { get; set; }
public int MaxItems { get; set; }
}
builder.Services.Configure<MySettings>(
builder.Configuration.GetSection("MySettings")
);
public class HomeController : Controller
{
private readonly MySettings _settings;
public HomeController(IOptions<MySettings> options)
{
_settings = options.Value;
}
}
3. Validate Options at Startup
builder.Services
.AddOptions<MySettings>()
.Bind(builder.Configuration.GetSection("MySettings"))
.Validate(settings => settings.MaxItems > 0, "MaxItems must be > 0");
4. Reloading Config on Changes
Enable hot reload for appsettings.json.
builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
Use IOptionsSnapshot<T> to get updated config per request.
5. Secret Management
Use User Secrets for local development.
dotnet user-secrets init
dotnet user-secrets set "MySettings:ApiKey" "123456"
builder.Configuration
.AddUserSecrets<Program>();
6. Azure Key Vault Integration
builder.Configuration.AddAzureKeyVault(
new Uri("https://yourvault.vault.azure.net/"),
new DefaultAzureCredential());
Make sure your app is registered and granted access to the vault.
7. Custom Configuration Provider
You can create a custom provider for things like databases or external services.
- Inherit from ConfigurationProvider and ConfigurationSource
- Inject it into the builder with the Add method
Points to consider
- Use IConfiguration for raw access to values
- Use IOptions for dependency injection & structured data
- Store secrets outside of source-controlled files
- Group related settings into sections