ASP.NET Core 8 Web API -

Configuration

ASP.NET Core Configuration is a fundamental concept that allows you to manage and access application settings efficiently. This tutorial will guide you through the various aspects of configuration in ASP.NET Core, ensuring a comprehensive understanding of how to work with configuration in your applications.


1. Introduction to ASP.NET Core Configuration

ASP.NET Core provides a flexible configuration framework that enables you to define and access settings from various sources such as JSON files, environment variables, command-line arguments, and more. The configuration system is designed to be extensible and supports a wide range of configuration providers.


2. Default Configuration Setup

When you create a new ASP.NET Core project, a default configuration setup is provided. This default setup includes reading configuration values from the appsettings.json file, environment-specific JSON files (e.g., appsettings.Development.json ), and environment variables.

        
            var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

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

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

app.UseAuthorization();

app.MapControllers();

app.Run();

        
    

This code snippet demonstrates how configuration is typically set up in a new ASP.NET Core project using WebApplication.CreateBuilder.


3. Configuration Providers

ASP.NET Core supports a variety of configuration providers. Each provider reads configuration data from a different source. Some common configuration providers are:


Adding JSON Configuration Provider

The JSON Configuration Provider reads configuration data from JSON files such as appsettings.json and appsettings.{Environment}.json.

        
            var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);

var app = builder.Build();
        
    
        
            {
  "ConnectionStrings": {
    "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
  },
  "AppSettings": {
    "PageSize": 10,
    "ApiKey": "12345",
    "Profile": {
       "UserName": "lorem",
       "Password": "somepassword"
    }
  },
  "Email": "santash92@gmail.com"
}
        
    

Adding Environment Variables Configuration Provider

The Environment Variables Configuration Provider reads configuration data from environment variables.

        
            # Example environment variable
var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddEnvironmentVariables();

var app = builder.Build();
        
    
        
            # Example environment variable
// Windows environment
setx MyConfigKey "MyValue"  # Sets the environment variable permanently on Windows

// Docker environment
ENV MyConfigKey="MyValue"  # In a Dockerfile, sets the environment variable

// Kubernetes environment
- name: MyConfigKey
  value: "MyValue"  # In a Kubernetes pod specification

// Linux environment
export MyConfigKey="MyValue"  # Sets the environment variable in a shell session

// Linux environment on systemd service
Environment="MyConfigKey=MyValue"  # In a systemd service file
        
    

Adding Command-Line Configuration Provider

The Command-Line Configuration Provider reads configuration data from command-line arguments.

        
            var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddCommandLine(args);

var app = builder.Build();
        
    
Where the Data is Stored:

The configuration data from the command-line arguments is stored in memory within the application's configuration system during runtime. It is not persisted to disk or any permanent storage. This in-memory storage allows the settings to be accessed throughout the application's lifecycle but they will be lost once the application stops.


        
            # Example command-line arguments
dotnet run --MySettingKey=MySettingValue
        
    

Adding User Secrets Configuration Provider

The User Secrets Configuration Provider reads configuration data from user secrets, which are ideal for storing sensitive data during development.

        
            var builder = WebApplication.CreateBuilder(args);

if (builder.Environment.IsDevelopment())
{
    builder.Configuration.AddUserSecrets<Program>();
}

var app = builder.Build();
        
    
        
            {
  "MySecretKey": "MySecretValue"
}
        
    
To manage user secrets:
Adding Azure Key Vault Configuration Provider

The Azure Key Vault Configuration Provider reads configuration data from Azure Key Vault, which is useful for securing sensitive information in a production environment.

        
            var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddAzureKeyVault(new Uri("https://<your-key-vault-name>.vault.azure.net/"), new DefaultAzureCredential());

var app = builder.Build();
        
    

Adding Azure App Configuration Provider

The Azure App Configuration Provider reads configuration data from Azure App Configuration, allowing you to centralize your configuration and manage it through the Azure portal.

        
            var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddAzureAppConfiguration("Endpoint=https://<your-config-store>.azconfig.io;Id=<id>;Secret=<secret>");

var app = builder.Build();
        
    

4. Reading Configuration Values

You can access configuration values using the IConfiguration interface. This interface is automatically available in the Startup class and can be injected into controllers, services, or any other part of your application.

Reading Configuration in Startup
        
            public class Startup
{
    private readonly IConfiguration _configuration;

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

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        // Example of reading configuration values
        var mySetting = _configuration["MySettingKey"];
    }
}
        
    

Reading Configuration in Controllers
        
            public class HomeController : Controller
{
    private readonly IConfiguration _configuration;

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

    public IActionResult Index()
    {
        var mySetting = _configuration["MySettingKey"];
        ViewData["MySetting"] = mySetting;
        return View();
    }
}
        
    

5. Environment-Specific Configuration

ASP.NET Core allows you to define environment-specific settings by creating environment-specific JSON files (e.g., appsettings.Development.json, appsettings.Staging.json, appsettings.Production.json). These settings will override the values in appsettings.json when the application is running in the specified environment.

Environment-Specific JSON File Example
        
            // appsettings.Production.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning"
    }
  },
  "MySettingKey": "ProductionValue"
}

        
    

        
            // appsettings.Staging.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning"
    }
  },
  "MySettingKey": "StagingValue"
}

        
    

        
            // appsettings.Development.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning"
    }
  },
  "MySettingKey": "DevelopmentValue"
}

        
    

6. Binding Configuration to Strongly Typed Objects (Options Pattern)

You can bind configuration values to strongly typed objects, which helps manage configuration settings more efficiently and makes your code easier to maintain.

Creating a Configuration Class
        
            public class MySettings
{
    public int PageSize { get; set; }
    public string ApiKey { get; set; }
}
        
    
Binding Configuration in Startup
        
            public class Startup
{
    private readonly IConfiguration _configuration;

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

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MySettings>(_configuration.GetSection("MySettings"));
        services.AddControllers();
    }
}

        
    
Accessing Strongly Typed Configuration in Controllers
        
            public class HomeController : Controller
{
    private readonly MySettings _mySettings;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _mySettings = mySettings.Value;
    }

    public IActionResult Index()
    {
        ViewData["PageSize"] = _mySettings.PageSize;
        ViewData["ApiKey"] = _mySettings.ApiKey;
        return View();
    }
}

        
    

7. Configuration in Azure App Services

When deploying an ASP.NET Core application to Azure App Services, you can manage configuration settings through the Azure portal. These settings can override values specified in your appsettings.json files.


Setting Environment Variables in Azure

8. Secure Configuration Data

Sensitive data such as connection strings and API keys should not be stored in plaintext in configuration files. Instead, consider using Azure Key Vault or other secure storage mechanisms to protect sensitive configuration data.

Using Azure Key Vault
        
            var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddAzureKeyVault(new Uri("https://<your-key-vault-name>.vault.azure.net/"), new DefaultAzureCredential());

var app = builder.Build();
        
    

9. Handling Missing Configuration

If you do not include configuration lines for adding JSON files or environment variables, your application will not read from those sources. This can lead to missing configuration values and potentially cause runtime errors.


Built-in Configuration Behavior

By default, ASP.NET Core reads configuration from appsettings.json, appsettings.{Environment}.json, and environment variables. If these are not included, you may need to handle missing configuration values manually in your code.


Conclusion

Understanding ASP.NET Core configuration is crucial for building robust and maintainable applications. By leveraging various configuration providers and following best practices, you can ensure that your application settings are managed effectively and securely.