MSDN Documentation

ASP.NET Core Configuration Fundamentals

This document provides a comprehensive overview of configuration in ASP.NET Core. Configuration is the process of making an application's settings external to its code. This allows you to manage settings for different environments (development, staging, production) without recompiling the application.

Key Concepts

Configuration Providers

The following table lists some of the commonly used configuration providers:

Provider Description Default Order
JSON Files Reads configuration from appsettings.json and environment-specific files (e.g., appsettings.Development.json). 1
Environment Variables Reads configuration from environment variables. 2
Command-line Arguments Reads configuration from command-line arguments passed to the application. 3
Azure Key Vault Integrates with Azure Key Vault for secure storage of secrets. -

Using the Configuration Builder

The Program.cs file typically initializes the configuration builder:


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

// Access configuration
var env = builder.Environment;
var config = builder.Configuration;

// Example of accessing a setting
string message = config["MySetting"];
Console.WriteLine($"MySetting: {message}");

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
            

The Options Pattern

To strongly type your configuration, define POCO classes that match the structure of your configuration sections. Then, register them with the dependency injection container.

1. Define your options class:


public class MyOptions
{
    public string Title { get; set; }
    public int PageSize { get; set; }
}
            

2. Bind configuration to your options class:


// In Program.cs or Startup.cs
builder.Services.Configure<MyOptions>(builder.Configuration.GetSection("MySection"));
            

3. Inject and use your options:


public class MyPageModel : PageModel
{
    private readonly IOptions<MyOptions> _options;

    public MyPageModel(IOptions<MyOptions> options)
    {
        _options = options;
    }

    public void OnGet()
    {
        ViewData["Title"] = _options.Value.Title;
        ViewData["PageSize"] = _options.Value.PageSize;
    }
}
            

Configuration Hierarchy and Access

Configuration values can be accessed using a key-value syntax, where keys can represent nested structures:

The order in which configuration providers are added is important. Later providers can override values from earlier providers.

Further Reading