Add feature flags to an ASP.NET Core app
In this post I will create an end-to-end implementation of feature management in an ASP.NET Core app using Azure App Configuration. You’ll 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
- You need Azure subscription, if you haven’t any create one for free
- Install .NET Core SDK
Create an App Configuration store
- To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home page, select Create a resource. In the Search the Marketplace box, enter App Configuration and select Enter.
Select App Configuration from the search results, and then select Create.
On the Create App Configuration pane, enter the following settings:
- Subscription: Your subscription
- Resource group: AppConfigTestResources
- Resource name: Globally unique name.
- Location: Central US
- Pricing tier: Freee
4. Select Review + create to validate your settings.
5. Select Create. The deployment might take a few minutes.
6. After the deployment finishes, navigate to the App Configuration resource. Select Settings > Access keys. Make a note of the primary read-only key connection string. You’ll use this connection string later to configure your application to communicate with the App Configuration store that you created.
7. Select Operations > Feature manager > Add to add a feature flag called Beta.
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 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.
Run the following command to create an ASP.NET Core MVC project in a new TestFeatureFlags folder:
dotnet user-secrets init
A UserSecretsId
element containing a GUID is added to the .csproj file:
<Project Sdk="Microsoft.NET.Sdk.Web"><br /> <PropertyGroup> <br /><TargetFramework>net6.0</TargetFramework> <br /><Nullable>enable</Nullable> <br /><ImplicitUsings>enable</ImplicitUsings><br /> <UserSecretsId>8296b5b7-6db3-4ae9-a590-899ac642c0d7</UserSecretsId> </PropertyGroup> </Project>
Tip: To learn more about Secret Manager, see Safe storage of app secrets in development in ASP.NET Core.
Connect to an App Configuration store
-
Install the Microsoft.Azure.AppConfiguration.AspNetCore and Microsoft.FeatureManagement.AspNetCore NuGet packages by running the following commands:
dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
dotnet add package Microsoft.FeatureManagement.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>"
-
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 (
3. In Program.cs, update the:
) works in the configuration name with the Configuration API on all supported platforms. For more information, see Configuration keys and values.CreateWebHostBuilder
method to use App Configuration by calling theAddAzureAppConfiguration
method.
Important: CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.x. Select the correct syntax based on your environment.
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => webBuilder.ConfigureAppConfiguration(config => <br />{ <br />var settings = config.Build(); var connection = settings.GetConnectionString("AppConfig"); config.AddAzureAppConfiguration(options => options.Connect(connection).UseFeatureFlags()); <br />}).UseStartup<Startup>());
With the preceding change, the configuration provider for App Configuration has been registered with the .NET Core Configuration API.
4. In Startup.cs, add a reference to the .NET Core feature manager:
using Microsoft.FeatureManagement;
5. Update the Startup.ConfigureServices
method to add feature flag support by calling the AddFeatureManagement
method. Optionally, you can include any filter to be used with feature flags by calling AddFeatureFilter<FilterType>
public void ConfigureServices(IServiceCollection services)<br /> { <br />services.AddControllersWithViews(); <br />services.AddFeatureManagement();
}
6. Add a MyFeatureFlags.cs file to the root project directory with the following code:
namespace TestFeatureFlags { public enum MyFeatureFlags { Beta } }
7. Add a BetaController.cs file to the Controllers directory with the following code:
using Microsoft.AspNetCore.Mvc;<br />using Microsoft.FeatureManagement;<br /> using Microsoft.FeatureManagement.Mvc;<br /> namespace TestFeatureFlags.Controllers <br />{ <br />public class BetaController: Controller<br /> { <br />private readonly IFeatureManager _featureManager;<br /> <br />public BetaController(IFeatureManagerSnapshot featureManager) => _featureManager = featureManager; [FeatureGate(MyFeatureFlags.Beta)] public IActionResult Index() => View(); <br /> }<br />}
8. In Views/_ViewImports.cshtml, register the feature manager Tag Helper using an @addTagHelper
directive:
@addTagHelper *, Microsoft.FeatureManagement.AspNetCore
9. The preceding code allows the <feature>
Tag Helper to be used in the project’s .cshtml files.Open _Layout.cshtml in the Views\Shared directory. Locate the <nav>
bar code under <body>
> <header>
. Insert a new <feature>
tag in between the Home and Privacy navbar items, as shown in the highlighted lines below.
In the HTML
<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>
10. Create a Views/Beta directory and an Index.cshtml file containing the following markup:
@{ ViewData["Title"] = "Beta Home Page"; }
<h1>This is the beta website.</h1>
Build and run the app locally
- 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 http://localhost:5000
, which is the default URL for the web app hosted locally. If you’re working in the Azure Cloud Shell, select the Web Preview button followed by Configure. When prompted, select port 5000.
Your browser should display a page similar to the image below.
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.
6. Enable the Beta flag by selecting the checkbox under Enabled.
7. Return to the command shell. Cancel the running dotnet
process by pressing Ctrl+C. Restart your app using dotnet run
.
Clean up resources
Clean up the created Resouces as following order.
- In the Filter by name box, enter the name of your resource group.
- In the result list, select the resource group name to see an overview.
- Select Delete resource group.
- 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.
Conclusion
In this post, I have created a feature management in an ASP.NET Core app, using Azure App Configuration and used it to manage features in an ASP.NET Core web app via the Feature Management libraries.
The .NET Core Feature Management libraries extend the framework with comprehensive feature flag support