Skip to content

Files

Latest commit

8564ca0 · Feb 15, 2022

History

History
250 lines (180 loc) · 11.6 KB

quickstart-aspnet-core-app.md

File metadata and controls

250 lines (180 loc) · 11.6 KB
title description services author ms.service ms.devlang ms.custom ms.topic ms.date ms.author
Quickstart for Azure App Configuration with ASP.NET Core | Microsoft Docs
Create an ASP.NET Core app with Azure App Configuration to centralize storage and management of application settings for an ASP.NET Core application.
azure-app-configuration
AlexandraKemperMS
azure-app-configuration
csharp
devx-track-csharp, contperf-fy21q1, mode-other
quickstart
1/3/2022
alkemper

Quickstart: Create an ASP.NET Core app with Azure App Configuration

In this quickstart, you'll use Azure App Configuration to centralize storage and management of application settings for an ASP.NET Core app. ASP.NET Core builds a single, key-value-based configuration object using settings from one or more data sources specified by an app. These data sources are known as configuration providers. Because App Configuration's .NET Core client is implemented as a configuration provider, the service appears like another data source.

Prerequisites

Tip

The Azure Cloud Shell is a free, interactive shell that you can use to run the command line instructions in this article. It has common Azure tools preinstalled, including the .NET Core SDK. If you're logged in to your Azure subscription, launch your Azure Cloud Shell from shell.azure.com. You can learn more about Azure Cloud Shell by reading our documentation

Create an App Configuration store

[!INCLUDEAzure App Configuration resource creation steps]

  1. Select Operations > Configuration explorer > Create > Key-value to add the following key-value pairs:

    Key Value
    TestApp:Settings:BackgroundColor #FFF
    TestApp:Settings:FontColor #000
    TestApp:Settings:FontSize 24
    TestApp:Settings:Message Data from Azure App Configuration

    Leave Label and Content type empty for now. Select Apply.

Create an ASP.NET Core web app

Use the .NET Core command-line interface (CLI) to create a new ASP.NET Core MVC project. The Azure Cloud Shell provides these tools for you. They're also available across the Windows, macOS, and Linux platforms.

Run the following command to create an ASP.NET Core MVC project in a new TestAppConfig folder:

dotnet new mvc --no-https --output TestAppConfig

[!INCLUDEAdd Secret Manager support to an ASP.NET Core project]

Connect to the App Configuration store

  1. Run the following command to add a Microsoft.Azure.AppConfiguration.AspNetCore NuGet package reference:

    dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
    
  2. Run the following command in the same directory as the .csproj file. The command uses Secret Manager to store a secret named ConnectionStrings:AppConfig, which stores the connection string for your App Configuration store. Replace the <your_connection_string> placeholder with your App Configuration store's connection string. You can find the connection string under Access Keys in the Azure portal.

    dotnet user-secrets set ConnectionStrings:AppConfig "<your_connection_string>"
    

    [!IMPORTANT] Some shells will truncate the connection string unless it's enclosed in quotes. Ensure that the output of the dotnet user-secrets list command shows the entire connection string. If it doesn't, rerun the command, enclosing the connection string in quotes.

    Secret Manager is used only to test the web app locally. When the app is deployed to Azure App Service, use the Connection Strings application setting in App Service instead of Secret Manager to store the connection string.

    Access this secret using the .NET Core Configuration API. A colon (:) works in the configuration name with the Configuration API on all supported platforms. For more information, see Configuration keys and values.

  3. Select the correct syntax based on your environment.

    In Program.cs, replace its content with the following code:

    var builder = WebApplication.CreateBuilder(args);
    //Retrieve the Connection String from the secrets manager 
    var connectionString = builder.Configuration.GetConnectionString("AppConfig");
    
    builder.Host.ConfigureAppConfiguration(builder =>
                    {
                        //Connect to your App Config Store using the connection string
                        builder.AddAzureAppConfiguration(connectionString);
                    })
                .ConfigureServices(services =>
                    {
                        services.AddControllersWithViews();
                    });
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles(); 
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    1. In Program.cs, add a reference to the .NET Core Configuration API namespace:

      using Microsoft.Extensions.Configuration;
    2. Update the CreateHostBuilder method to use App Configuration by calling the AddAzureAppConfiguration method.

      public static IHostBuilder CreateHostBuilder(string[] args) =>
          Host.CreateDefaultBuilder(args)
              .ConfigureWebHostDefaults(webBuilder =>
                  webBuilder.ConfigureAppConfiguration(config =>
                  {
                      var settings = config.Build();
                      var connection = settings.GetConnectionString("AppConfig");
                      config.AddAzureAppConfiguration(connection);
                  }).UseStartup<Startup>());

    [!IMPORTANT] CreateHostBuilder in .NET 3.x replaces CreateWebHostBuilder in .NET Core 2.x.

    1. In Program.cs, add a reference to the .NET Core Configuration API namespace:

      using Microsoft.Extensions.Configuration;
    2. Update the CreateHostBuilder method to use App Configuration by calling the AddAzureAppConfiguration method.

      public static IHostBuilder CreateHostBuilder(string[] args) =>
          Host.CreateDefaultBuilder(args)
              .ConfigureWebHostDefaults(webBuilder =>
                  webBuilder.ConfigureAppConfiguration(config =>
                  {
                      var settings = config.Build();
                      var connection = settings.GetConnectionString("AppConfig");
                      config.AddAzureAppConfiguration(connection);
                  }).UseStartup<Startup>());
    1. In Program.cs, add a reference to the .NET Core Configuration API namespace:

      using Microsoft.Extensions.Configuration;
    2. Update the CreateWebHostBuilder method to use App Configuration by calling the AddAzureAppConfiguration method.

      public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
          WebHost.CreateDefaultBuilder(args)
              .ConfigureAppConfiguration(config =>
              {
                  var settings = config.Build();
                  var connection = settings.GetConnectionString("AppConfig");
                  config.AddAzureAppConfiguration(connection);
              })
              .UseStartup<Startup>();

This code will connect to your App Configuration store using a connection string and load all key-values. For more information on the configuration provider APIs, reference the configuration provider for App Configuration docs.

Read from the App Configuration store

Complete the following steps to read and display values stored in the App Configuration store. The .NET Core Configuration API will be used to access the store. Razor syntax will be used to display the keys' values.

Open <app root>/Views/Home/Index.cshtml, and replace its content with the following code:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<style>
    body {
        background-color: @Configuration["TestApp:Settings:BackgroundColor"]
    }
    h1 {
        color: @Configuration["TestApp:Settings:FontColor"];
        font-size: @Configuration["TestApp:Settings:FontSize"]px;
    }
</style>

<h1>@Configuration["TestApp:Settings:Message"]</h1>

In the preceding code, the App Configuration store's keys are used as follows:

  • The TestApp:Settings:BackgroundColor key's value is assigned to the CSS background-color property.
  • The TestApp:Settings:FontColor key's value is assigned to the CSS color property.
  • The TestApp:Settings:FontSize key's value is assigned to the CSS font-size property.
  • The TestApp:Settings:Message key's value is displayed as a heading.

Build and run the app locally

  1. To build the app using the .NET Core CLI, navigate to the root directory of your project. Run the following command in the command shell:

    dotnet build
    
  2. After the build completes successfully, run the following command to run the web app locally:

    dotnet run
    
  3. If you're working on your local machine, use a browser to navigate to http://localhost:5000 or as specified in the command output. This address is the default URL for the locally hosted web app. If you're working in the Azure Cloud Shell, select the Web Preview button followed by Configure.

    Locate the Web Preview button

    When prompted to configure the port for preview, enter 5000 and select Open and browse. The web page will read "Data from Azure App Configuration."

Clean up resources

[!INCLUDEAzure App Configuration cleanup]

Next steps

In this quickstart, you:

  • Provisioned a new App Configuration store.
  • Registered the App Configuration store's .NET Core configuration provider.
  • Read the App Configuration store's keys with the configuration provider.
  • Displayed the App Configuration store's key values using Razor syntax.

To learn how to configure your ASP.NET Core app to dynamically refresh configuration settings, continue to the next tutorial.

[!div class="nextstepaction"] Enable dynamic configuration