Quickstart: Add feature flags to an ASP.NET Core app

In this quickstart, you incorporate Azure App Configuration into an ASP.NET Core web app to create an end-to-end implementation of feature management. You can use the App Configuration service to centrally store all your feature flags and control their states.

The .NET Core Feature Management libraries extend the framework with comprehensive feature flag support. These libraries are built on top of the .NET Core configuration system. They seamlessly integrate with App Configuration through its .NET Core configuration provider.

Prerequisites

Create an App Configuration store

  1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the pane, select +Create a resource. In the Search the Marketplace box, enter App Configuration and select Enter.

    Search for App Configuration

  2. Select App Configuration from the search results, and then select Create.

  3. On the App Configuration > Create pane, enter the following settings:

    Setting Suggested value Description
    Resource name Globally unique name Enter a unique resource name to use for the App Configuration store resource. The name must be a string between 1 and 63 characters and contain only numbers, letters, and the - character. The name can't start or end with the - character, and consecutive - characters aren't valid.
    Subscription Your subscription Select the Azure subscription that you want to use to test App Configuration. If your account has only one subscription, it's automatically selected and the Subscription list isn't displayed.
    Resource group AppConfigTestResources Select or create a resource group for your App Configuration store resource. This group is useful for organizing multiple resources that you might want to delete at the same time by deleting the resource group. For more information, see Use resource groups to manage your Azure resources.
    Location Central US Use Location to specify the geographic location in which your app configuration store is hosted. For the best performance, create the resource in the same region as other components of your application.

    Create an App Configuration store resource

  4. Select Create. The deployment might take a few minutes to finish.

  5. After the deployment is finished, select Settings > Access Keys. Make a note of either the primary read-only or primary read-write key connection string. You'll use this connection string later to configure your application to communicate with the App Configuration store that you created.

  1. Select Feature Manager > +Create to add the following feature flags:

    Key State
    Beta Off

Create an ASP.NET Core web app

You use the .NET Core command-line interface (CLI) to create a new ASP.NET Core MVC web app project. The advantage of using the .NET Core CLI instead of Visual Studio is that the .NET Core CLI is available across the Windows, macOS, and Linux platforms.

  1. Create a new folder for your project. For this quickstart, name it TestFeatureFlags.

  2. In the new folder, run the following command to create a new ASP.NET Core MVC web app project:

    dotnet new mvc
    

Add Secret Manager

Add the Secret Manager tool to your project. The Secret Manager tool stores sensitive data for development work outside your project tree. This approach helps prevent the accidental sharing of app secrets within source code.

  1. Open the .csproj file.

  2. Add a UserSecretsId element as shown in the following example, and replace its value with your own, which typically is a GUID:

    <Project Sdk="Microsoft.NET.Sdk.Web">
    
    <PropertyGroup>
        <TargetFramework>netcoreapp2.1</TargetFramework>
        <UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>
    </PropertyGroup>
    
    <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.App" />
        <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
    </ItemGroup>
    
    </Project>
    
  3. Save the file.

Connect to an App Configuration store

  1. Add reference to the Microsoft.Azure.AppConfiguration.AspNetCore NuGet package by running the following command:

    dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore --version 2.0.0-preview-009200001-7
    
  2. Run the following command to restore packages for your project:

    dotnet restore
    
  3. Add a secret named ConnectionStrings:AppConfig to Secret Manager.

    This secret contains the connection string to access your App Configuration store. Replace the <your_connection_string> value in the following command with the connection string for your App Configuration store.

    This command must be executed in the same directory as the .csproj file.

    dotnet user-secrets set ConnectionStrings:AppConfig <your_connection_string>
    

    You use Secret Manager only to test the web app locally. When you deploy the app to Azure App Service, for example, you use an application setting named Connection Strings in App Service instead of using Secret Manager to store the connection string.

    You can access this secret with the App Configuration API. A colon (:) works in the configuration name with the App Configuration API on all supported platforms. See Configuration by environment.

  4. Open Program.cs, and add a reference to the .NET Core App Configuration provider:

    using Microsoft.Extensions.Configuration.AzureAppConfiguration;
    
  5. Update the CreateWebHostBuilder method to use App Configuration by calling the config.AddAzureAppConfiguration() method.

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var settings = config.Build();
                config.AddAzureAppConfiguration(options => {
                    options.Connect(settings["ConnectionStrings:AppConfig"])
                           .UseFeatureFlags();
                });
            })
            .UseStartup<Startup>();
    
  6. Open Startup.cs, and add references to the .NET Core feature manager:

    using Microsoft.FeatureManagement;
    
  7. Update the ConfigureServices method to add feature flag support by calling the services.AddFeatureManagement() method. Optionally, you can include any filter to be used with feature flags by calling services.AddFeatureFilter<FilterType>():

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddFeatureManagement();
    }
    
  8. Update the Configure method to add a middleware to allow the feature flag values to be refreshed at a recurring interval while the ASP.NET Core web app continues to receive requests.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAzureAppConfiguration();
        app.UseMvc();
    }
    
  9. Add a MyFeatureFlags.cs file:

    namespace TestFeatureFlags
    {
        public enum MyFeatureFlags
        {
            Beta
        }
    }
    
  10. Add BetaController.cs to the Controllers directory:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.FeatureManagement;
    using Microsoft.FeatureManagement.Mvc;
    
    namespace TestFeatureFlags.Controllers
    {
        public class BetaController: Controller
        {
            private readonly IFeatureManager _featureManager;
    
            public BetaController(IFeatureManagerSnapshot featureManager)
            {
                _featureManager = featureManager;
            }
    
            [FeatureGate(MyFeatureFlags.Beta)]
            public IActionResult Index()
            {
                return View();
            }
        }
    }
    
  11. Open _ViewImports.cshtml in the Views directory, and add the feature manager tag helper:

    @addTagHelper *, Microsoft.FeatureManagement.AspNetCore
    
  12. Open _Layout.cshtml in the Views\Shared directory, and replace the <nav> bar code under <body> > <header> with the following code:

    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">TestFeatureFlags</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
            aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                    </li>
                    <feature name="Beta">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Beta" asp-action="Index">Beta</a>
                    </li>
                    </feature>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    
  13. Create a Beta directory under Views and add Index.cshtml to it:

    @{
        ViewData["Title"] = "Beta Home Page";
    }
    
    <h1>
        This is the beta website.
    </h1>
    

Build and run the app locally

  1. To build the app by using the .NET Core CLI, run the following command in the command shell:

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

    dotnet run
    
  3. Open a browser window, and go to https://localhost:5001, which is the default URL for the web app hosted locally.

    Quickstart app launch local

  4. Sign in to the Azure portal. Select All resources, and select the App Configuration store instance that you created in the quickstart.

  5. Select Feature Manager, and change the state of the Beta key to On:

    Key State
    Beta On
  6. Refresh the browser page to see the new configuration settings.

    Quickstart app launch local

Clean up resources

If you plan to continue to the next tutorial, keep the resources you created in this quickstart. You can reuse them in the next tutorial.

If you're finished with the quickstart sample application, delete the Azure resources you created in this quickstart to avoid charges.

Important

Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure that you don't accidentally delete the wrong resource group or resources. If you created the resources for hosting this sample inside a resource group that contains resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.

  1. Sign in to the Azure portal, and select Resource groups.
  2. In the Filter by name box, enter the name of your resource group. The instructions for this quickstart used a resource group named AppConfigTestResources.
  3. In the result list, select the resource group, and either right-click the row or use the ellipsis (...) button to open the context menu.
  4. Select Delete resource group.
  5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm, and select Delete.

After a few moments, the resource group and all its resources are deleted.

Next steps

In this quickstart, you created a new App Configuration store and used it to manage features in an ASP.NET Core web app via the Feature Management libraries.