MSDN Documentation

ASP.NET Core Configuration

ASP.NET Core Configuration

This document provides a comprehensive guide to configuring ASP.NET Core applications. Configuration is a fundamental aspect of any application, allowing you to manage settings that vary across environments, such as connection strings, API keys, and feature flags.

Introduction to Configuration Providers

ASP.NET Core utilizes a flexible configuration system that allows you to load settings from various sources, known as configuration providers. These providers can include:

The configuration system reads settings in a specific order, and later providers can override settings from earlier ones. This allows for a hierarchical and predictable configuration management.

Core Concepts

Configuration Root

The configuration root represents the top-level container for all configuration settings. It's typically an instance of IConfiguration.

Configuration Sections

Configuration settings can be organized into sections, mirroring the structure of JSON files or logical groupings of related settings.

Key-Value Pairs

Configuration settings are stored as key-value pairs. Keys can be hierarchical, using a colon (:) as a separator (e.g., Logging:LogLevel:Default).

Working with Configuration Files (appsettings.json)

The appsettings.json file is the default configuration file. It's typically placed in the root of your project. You can also have environment-specific configuration files, such as appsettings.Development.json or appsettings.Production.json.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApiSettings": {
    "ApiKey": "YOUR_DEFAULT_API_KEY",
    "EndpointUrl": "https://api.example.com/v1"
  }
}

The ASP.NET Core Kestrel web server automatically loads appsettings.json and environment-specific configuration files by default.

Accessing Configuration in Your Application

Using IConfiguration

The most direct way to access configuration is by injecting IConfiguration into your classes:

public class MyService : IMyService
{
    private readonly IConfiguration _configuration;

    public MyService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void DoSomething()
    {
        var apiKey = _configuration["ApiSettings:ApiKey"];
        var logLevel = _configuration["Logging:LogLevel:Default"];
        Console.WriteLine($"API Key: {apiKey}");
        Console.WriteLine($"Log Level: {logLevel}");
    }
}

Options Pattern

For better type safety and organization, the Options pattern is highly recommended. You define classes that map to specific configuration sections.

First, define your options class:

public class ApiSettings
{
    public string ApiKey { get; set; }
    public string EndpointUrl { get; set; }
}

Then, configure the options in Program.cs (or Startup.cs for older templates) and register it with the dependency injection container:

builder.Services.Configure<ApiSettings>(builder.Configuration.GetSection("ApiSettings"));

Finally, inject and use the options class:

public class AnotherService : IAnotherService
{
    private readonly ApiSettings _apiSettings;

    public AnotherService(IOptions<ApiSettings> apiSettingsOptions)
    {
        _apiSettings = apiSettingsOptions.Value;
    }

    public void MakeApiCall()
    {
        Console.WriteLine($"Calling API at: {_apiSettings.EndpointUrl} with Key: {_apiSettings.ApiKey}");
    }
}

Environment Variables

Environment variables provide a way to override configuration settings, especially in deployed environments. ASP.NET Core automatically reads environment variables. Keys are typically represented with double underscores (__) as separators, which map to colons in the configuration hierarchy (e.g., ASPNETCORE_ENVIRONMENT, Logging__LogLevel__Default).

Command-Line Arguments

You can pass configuration values via command-line arguments when starting your application. The format is typically --Key:SubKey Value or --Key.SubKey Value.

dotnet run --ApiSettings:ApiKey=MY_RUNTIME_API_KEY

Best Practices

Conclusion

The ASP.NET Core configuration system is powerful and flexible, enabling you to manage application settings effectively across different environments. By understanding configuration providers, the Options pattern, and best practices, you can build robust and maintainable applications.