How to use feature flags in ASP.NET Core

Take advantage of feature flags to easily enable and disable features in your application without changing its codebase.

How to use feature flags in ASP.NET Core
Getty Images

The .NET Core Feature Management library can be used to implement feature flags in an ASP.NET Core application. You can then use feature flags to change the behavior of your application without the need to change anything in the codebase. This article presents a discussion of how we can work with this library in ASP.NET Core.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here

Create an ASP.NET Core API project

First off, let’s create an ASP.NET Core project in Visual Studio 2019. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of the templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create. 
  7. In the “Create New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top. I’ll be using ASP.NET Core 3.0 here.
  8. Select “API” as the project template to create a new ASP.NET Core API application. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  11. Click Create.

You should now have a new ASP.NET Core API project ready to go in Visual Studio. Next, select the Controllers solution folder in the Solution Explorer window and click “Add -> Controller…” to create a new controller named DefaultController.

We’ll use this project in the subsequent sections of this article.

Install the FeatureManagement NuGet package

Now that we have created an ASP.NET Core application in Visual Studio, the next thing you should do is install the necessary NuGet package. To work with feature management in ASP.NET Core, you should have the Microsoft.FeatureManagement.AspNetCore package installed in your project.

You can install this package from the NuGet Package Manager inside the Visual Studio 2019 IDE. Alternatively, you can enter the following command to install this package via the .NET CLI.

dotnet add package Microsoft.FeatureManagement.AspNetCore

Note that the FeatureManagement package is still in preview, so you should check the “Include prerelease” check box as shown in Figure 1 to be able to see this package in the NuGet Package Manager window.

aspnet core featuremanagement IDG

Figure 1: Installing packages via the NuGet Package Manager.

Add Feature Management support in ASP.NET Core

To add support for feature management in your application, write the following code in the ConfigureServices method of the Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    services.AddFeatureManagement();
}

Note that the feature manager will retrieve the feature flags from the FeatureManagement section of your .NET Core configuration file. If you want to read the feature flags from a different section of the file, you should write the following code in the ConfigureServices method of Startup class.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddFeatureManagement(options =>
        {
                options.UseConfiguration
               (Configuration.GetSection("IDGFeatureFlags"));
        });
    }

Use feature management in controllers in ASP.NET Core

You can take advantage of dependency injection to be able to work with the feature management capabilities in your controllers as shown in the code snippet given below.

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
   private readonly IFeatureManager _featureManager;
   public ValuesController(IFeatureManagerSnapshot featureManager)
   {
       _featureManager = featureManager;
   }
   //Write your action methods here
}

Now add a section named FeatureManagement in the appsettings.json file. You can replace the entire contents of the generated appsettings.json file with the following code:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "FeatureManagement": {
    "DbLogger": "true"
  },
  "AllowedHosts": "*"
}

Use the FeatureGate attribute to enable and disable features in ASP.NET Core

Use the FeatureGate attribute to restrict the execution of an action method as shown in the code snippet given below. The HttpGet action method will be executed if DbLogger is turned on. If DbLogger is turned off, the action method will throw an HTTP 404 error.

 [Route("api/[controller]")]
 [ApiController]
 public class ValuesController : ControllerBase
  {
    private readonly IFeatureManager _featureManager;
    public ValuesController(IFeatureManagerSnapshot featureManager)
    {
       _featureManager = featureManager;
    }
    [FeatureGate("DbLogger")]
    [HttpGet]
    public ActionResult<string> Get()
    {
       return "Hello World!";
    }
      //Other action methods
  }

When you execute the application, the message “Hello World!” will be displayed in the web browser when the DbLogger feature flag is turned on. If the feature flag is turned off, you’ll be greeted with an HTTP 404 error as shown in Figure 2 below.

aspnet core featuremanagement 404 IDG

Figure 2: HTTP 404 error when accessing a feature that is disabled. 

Microsoft .NET Core has support for feature management out of the box. To work with feature management in ASP.NET Core, simply install the Microsoft.FeatureManagement.AspNetCore package in your project and follow the configuration steps I have outlined above. You can learn more about feature management in ASP.NET Core from Microsoft’s online tutorial

Copyright © 2019 IDG Communications, Inc.