How to create a custom feature filter in ASP.NET Core
Tags: aspnetcore, customfeaturefilters, featureflags
Published: 2022-11-05 16:13:23

---
title: How to create a custom feature filter in ASP.NET Core
published: true
date: 2022-10-10 07:56:15 UTC
tags: ASPNETCore,customfeaturefilters,featureflags
canonical_url: https://coderethinked.com/how-to-create-a-custom-feature-filter-in-asp-net-core/
---

While feature flags allow us to turn a feature on/off in real-time without any code changes. Feature filters go one level deep on the feature flags.

**Feature filters allow us to filter/limit a feature to a specific group**. This allows us to control who has access to the features.

Ex: We can limit the number of people who can see the feature or we can show the feature when the temperature is too hot. You can pretty much do like an if-this-then-that kind of thing with it.

There are three default feature filters available in ASP.NET Core. However, we can create custom feature filters.

In this post, we will see how to create a new custom feature filter with `FeatureManagement` package.

**Takeaways**

1. What are custom feature flags and uses.

2. By the end of this article, you should be able to create a custom feature filter and configure the necessary steps required to make it work.

## Prerequisite

If you are unaware of what feature management or feature flags are you should first consider reading our [comprehensive guide to feature management in asp.net core](https://dev.to/karthikchintala/the-comprehensive-guide-to-feature-management-in-aspnet-core-3iom-temp-slug-8401658).

A prior understanding of feature management will make it easy to understand custom feature filters in asp.net core.

## Use Case for custom feature filter

Let’s say we want to show a secret feature to only specific people in the organization.

For this article, I’ll create a new asp.net core application with asp.net core identity and create a couple of users. I’m not going to show you how to create users, asp.net core identity, or a new application as it is out of the scope of this article.

## Quick Glance at Creating Custom Feature Filter

Before we dive in and write code to create a custom feature filter. Here is what we will be doing in this article.

![quick overview of creating Custom feature filters infographic](https://coderethinked.com/wp-content/uploads/2022/10/quick-overview-of-creating-Custom-feature-filters-infographic.png)

## Custom feature filter setup in appsettings.json file

Unlike the standard boolean feature flag which is set to either true/false, the custom feature flag is configured differently.

Here is how we configure our custom user feature filter

```json
"FeatureManagement": {
    "SecretFeature": {
      "EnabledFor": [
        {
          "Name": "UserFeature",
          "Parameters": {
            "Email": ["karthik@coderethinked.com"]
          }
        }
      ]
    }
  }
```

### Understanding EnabledFor section in Feature Management

Notice how the `EnabledFor` section is declared in the above `appsettings.json` file. We created an array of objects for `EnabledFor` property.

We can have multiple filters for the same feature flag item. If we declare multiple objects in the `EnabledFor` array they all would work like an OR filter for the feature flag.

Every object within the array of items in `EnabledFor` should have these two properties

1. **Name** : The name of our custom feature filter. The name should match any of the custom feature filters we create.  
In the above example, we declared the filter name as UserFeature. So, it looks for a feature filter class with the name “UserFeatureFilter” (Filter suffix is a convention here)
2. **Parameters** : This is where we set data for our filter. We can have multiple properties within the Parameters object and the properties can be of any type.   
In the example above, Email is an array of items. For accessing the parameter values, we can create a settings class and get a strongly typed object out of it.

## Creating a feature filter class

Assuming you have prior knowledge of how to install the `Microsoft.FeatureManagement` package and setting it up a feature flag. If you don’t, please check [this article](https://dev.to/karthikchintala/the-comprehensive-guide-to-feature-management-in-aspnet-core-3iom-temp-slug-8401658).

Let’s create a custom feature filter for the user filter.

To create a custom filter we have to implement the `IFeatureFilter` interface in our `UserFeatureFilter` class.

The `IFeatureFilter` interface has `EvaluateAsync` method which has to be implemented and it returns a boolean. The result of the method serves as the value of the feature flag for the current request.

Here is our `UserFeatureFilter` class.

```csharp
public class UserFeatureFilter : IFeatureFilter
{
	private readonly IHttpContextAccessor _httpContextAccessor;

	public UserFeatureFilter(IHttpContextAccessor accessor)
	{
		_httpContextAccessor = accessor;
	}

	public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context)
	{
		var settings = context.Parameters.Get<UserFilterSettings>();
		var userIdentity = _httpContextAccessor.HttpContext?.User?.Identity;

		return Task.FromResult(settings.Email.Contains(userIdentity?.Name));
	}
}
```

And here is our UserFilterSettings class

```csharp
public class UserFilterSettings
{
	public string[] Email { get; set; }
}
```

We are getting the parameters (Email) that are set for the filter in the `appsettings.json` file and we are matching the user identity name within the email array.

To know the user name from the HttpContext, we injected `IHttpContextAccessor` as a dependency to our filter class and the interface has to be registered in the startup.cs file.

`IHttpContextAccessor` should be used with caution. Our HttpContext on the `IHttpContextAccessor` instance may go null if there is no HttpContext.

## Registering our custom feature flag in the startup.cs file

Let’s register our custom feature filter we created in the startup class and also the IHttpContextAccessor.

Within the ConfigureServices method, we register them like this:

```csharp
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddFeatureManagement().AddFeatureFilter<UserFeatureFilter>();
```

And that’s it!

## Demo

<video id="video-863-1" width="640" height="360" preload="metadata" controls="controls"><source type="video/mp4" src="https://i.imgur.com/wo5Bmii.mp4?_=1"></source><a href="https://i.imgur.com/wo5Bmii.mp4">https://i.imgur.com/wo5Bmii.mp4</a></video>

That’s it! Thanks for reading.

## References

- [IFeatureFilter interface](https://learn.microsoft.com/en-us/dotnet/api/microsoft.featuremanagement.ifeaturefilter?view=azure-dotnet-preview)
- [IHttpContextAccessor interface](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.ihttpcontextaccessor?view=aspnetcore-7.0)
- [Feature Flag Declaration](https://learn.microsoft.com/en-us/azure/azure-app-configuration/use-feature-flags-dotnet-core?tabs=core5x#feature-flag-declaration)
- [Comprehensive Guide to feature management in ASP.NET Core](https://dev.to/karthikchintala/the-comprehensive-guide-to-feature-management-in-aspnet-core-3iom-temp-slug-8401658)

The post [How to create a custom feature filter in ASP.NET Core](https://coderethinked.com/how-to-create-a-custom-feature-filter-in-asp-net-core/) appeared first on [Code Rethinked](https://coderethinked.com).