Feature flags in ASP.NET Core

In this article, I’ll show an example of using a feature flag to toggle an endpoint on/off with a configuration value in appsettings.json.

1 – Install feature management package

Install the Microsoft.FeatureManagement.AspNetCore package. Note: This is using (View > Other Windows > Package Manager Console).

Install-Package Microsoft.FeatureManagement.AspNetCore
Code language: PowerShell (powershell)

2 – Add feature flags to appsettings.json

Edit appsettings.json and add section FeatureManagement. Add bool properties for each feature flag you want to use. In this example, we have one feature flag called WeatherForecast:

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



Code language: JSON / JSON with Comments (json)

FeatureManagement is the default section name that ASP.NET Core looks for when loading feature flags.

3 – Enable feature management

In the initialization code, enable feature management by calling builder.Services.AddFeatureManagement():

using Microsoft.FeatureManagement;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddFeatureManagement();

var app = builder.Build();

//rest of init
Code language: C# (cs)

Note: Before .NET 6, do this in Startup.ConfigureServices().

By default, this’ll load feature flags from the FeatureManagement section from appsettings.json.

4 – Use FeatureGate attribute

You can use feature flags to toggle code blocks on/off, from entire controllers all the way down to individual lines of code. One common and practical use case for feature flags is feature gating an endpoint. You can do this with the FeatureGate attribute and specifying the name of the feature flag. Here’s an example:

using Microsoft.FeatureManagement.Mvc;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
	[HttpGet]
	[FeatureGate("WeatherForecast")]
	public WeatherForecast Get()
	{
		return new WeatherForecast() { Summary = "Sunny" };
	}
}
Code language: C# (cs)

When the WeatherForecast feature flag is enabled (true) in appsettings.json, the endpoint will execute and return a response like normal. When it’s disabled (false), it’ll return a 404 (Not Found).

Leave a Comment