Azure App Configuration for ASP.NET: A Complete Guide to Centralized Configuration Management

Externalizing properties (or configurations) in an ASP.NET application to an Azure App Configuration store allows for centralized configuration management, easier updates, and improved security. Here's a complete guide to set this up:



Step 1: Create an Azure App Configuration Store

  1. Log in to Azure Portal.
  2. Search for "App Configuration" in the search bar and click on it.
  3. Click on "Create" and provide the following details:
    • Subscription: Select your Azure subscription.
    • Resource Group: Select an existing resource group or create a new one.
    • Name: Provide a unique name for the App Configuration store.
    • Region: Choose your preferred region.
  4. Click "Review + Create" and then "Create".

Step 2: Add Configuration Settings in Azure

  1. Go to your App Configuration store in the Azure Portal.
  2. Navigate to "Configuration Explorer".
  3. Click "Create" to add a new key-value pair.
    • Key: The name of your configuration property (e.g., AppSettings:DatabaseConnectionString).
    • Value: The value of the configuration property (e.g., your connection string).
    • Label: Optionally, add a label to distinguish different environments (e.g., Development, Production).

Step 3: Add NuGet Packages in ASP.NET Application

  1. Open your ASP.NET project in Visual Studio.
  2. Add the following NuGet packages:
    • Microsoft.Extensions.Configuration.AzureAppConfiguration
    • Microsoft.Azure.AppConfiguration.AspNetCore

Use the Package Manager Console or NuGet Manager UI to install them:

Install-Package Microsoft.Extensions.Configuration.AzureAppConfiguration
Install-Package Microsoft.Azure.AppConfiguration.AspNetCore

Step 4: Register Azure App Configuration in Startup

  1. In your Program.cs or Startup.cs (depending on your project type), modify the configuration setup:

For .NET Core 6.0 and later:

var builder = WebApplication.CreateBuilder(args);

// Add Azure App Configuration
builder.Configuration.AddAzureAppConfiguration(options =>
{
    options.Connect("<Your_Connection_String>")
           .Select(KeyFilter.Any, LabelFilter.NullOrAny);
});

var app = builder.Build();

// Use Azure App Configuration
app.UseAzureAppConfiguration();

app.MapControllers();
app.Run();

For .NET Core 3.1 and earlier:

public class Startup
{
    public IConfiguration Configuration { get; }

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

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAzureAppConfiguration();
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseAzureAppConfiguration();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

Step 5: Connect to Azure App Configuration

  1. Obtain the connection string for your App Configuration store:

    • Go to your App Configuration store in Azure.
    • Navigate to "Access Keys".
    • Copy the Connection String.
  2. Add the connection string to your local development environment's appsettings.json or secrets.json file:

    {
      "AzureAppConfiguration": {
        "ConnectionString": "Your-Connection-String"
      }
    }

    Alternatively, use an environment variable for production.


Step 6: Access Configuration Properties in Code

You can now access your configurations using IConfiguration:

Example:

public class HomeController : Controller
{
    private readonly IConfiguration _configuration;

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

    public IActionResult Index()
    {
        var connectionString = _configuration["AppSettings:DatabaseConnectionString"];
        ViewBag.ConnectionString = connectionString;

        return View();
    }
}

Step 7: Enable Dynamic Configuration Updates (Optional)

To enable dynamic configuration updates without restarting your app:

  1. Modify your configuration setup in Program.cs:

    builder.Configuration.AddAzureAppConfiguration(options =>
    {
        options.Connect("<Your_Connection_String>")
               .UseFeatureFlags() // Optional for feature flags
               .ConfigureRefresh(refresh =>
               {
                   refresh.Register("AppSettings:DatabaseConnectionString", LabelFilter.NullOrAny, refreshAll: true);
               });
    });
  2. Use IOptionsSnapshot<T> for dynamically updated configurations in your services.


Step 8: Secure Access with Managed Identity (Recommended)

Instead of using a connection string, you can use Azure Managed Identity:

  1. Assign a Managed Identity to your Azure App Service or Virtual Machine.
  2. Grant the identity "App Configuration Data Reader" role in the App Configuration store.
  3. Modify your configuration setup:
    builder.Configuration.AddAzureAppConfiguration(options =>
    {
        options.Connect(new Uri("https://<Your-App-Config-Store>.azconfig.io"), new DefaultAzureCredential());
    });


Your ASP.NET application is now configured to use Azure App Configuration for centralized property management. This setup allows you to manage settings dynamically, implement feature flags, and maintain security using best practices like Managed Identity.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete