Skip to content
  • English Deutsch

benjamin-abt.com

Performance is a feature | Cloud - AI - Azure - .NET - Sustainability

  • Home
  • Blog
  • Portfolio
    • Overview
    • Workshops & Training
    • Publications
  • Contact
  • Home
  • Blog

Build a Custom FeatureGate Attribute in ASP.NET Core with C#

Build a Custom FeatureGate Attribute in ASP.NET Core with C#
January 2, 2026 4 min read BEN ABT
ASP.NET Core Csharp .NET

Feature management is a key technique in modern web applications, allowing you to enable or disable features dynamically without redeploying your code. In ASP.NET Core, the Microsoft.FeatureManagement library provides a robust way to implement feature flags. But what if you want to ensure that administrators can always access certain features, even if those features are disabled for regular users?

In this post, you’ll learn how to build a custom FeatureGate attribute in ASP.NET Core using C#. This attribute will:

  • Allow users with a specific claim (“platformadmin”) to bypass feature flag checks.
  • Enforce feature flag evaluation for all other users.
  • Provide a flexible way to handle disabled features.

Why customize feature gates?

The default feature gate implementation in ASP.NET Core is great for most scenarios. But sometimes, business requirements demand that certain users (like admins) always have access, regardless of feature flag state. By customizing the feature gate, you can implement these advanced rules.

The custom attribute: PlatformFeatureGateAttribute

Below is the implementation of a custom attribute called PlatformFeatureGateAttribute. This attribute checks if the current user is authenticated and has the platformadmin claim. If so, the user bypasses the feature flag check. Otherwise, the feature flag is evaluated as usual.

C#
 1using Microsoft.AspNetCore.Mvc;
 2using Microsoft.AspNetCore.Mvc.Filters;
 3using Microsoft.FeatureManagement;
 4using System;
 5using System.Linq;
 6using System.Threading.Tasks;
 7
 8[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
 9public class PlatformFeatureGateAttribute : Attribute, IAsyncActionFilter
10{
11    public string Feature { get; set; }
12
13    public PlatformFeatureGateAttribute(string feature)
14    {
15        Feature = feature ?? throw new ArgumentNullException(nameof(feature));
16    }
17
18    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
19    {
20        // Check if user is authenticated and has the "platformadmin" claim
21        var user = context.HttpContext.User;
22        if (user?.Identity?.IsAuthenticated == true &&
23            user.Claims.Any(c => c.Type == "platformadmin" && c.Value == "true"))
24        {
25            // Admin users bypass feature gate check
26            await next();
27            return;
28        }
29
30        // For non-admin users, perform normal feature flag check
31        var featureManager = context.HttpContext.RequestServices.GetService(typeof(IFeatureManager)) as IFeatureManager;
32
33        if (featureManager == null)
34        {
35            context.Result = new ForbidResult();
36            return;
37        }
38
39        bool isEnabled = await featureManager.IsEnabledAsync(Feature);
40
41        if (isEnabled)
42        {
43            await next();
44        }
45        else
46        {
47            // Feature is disabled - handle accordingly
48            var handler = context.HttpContext.RequestServices.GetService(typeof(IDisabledFeaturesHandler)) as IDisabledFeaturesHandler;
49
50            if (handler != null)
51            {
52                await handler.HandleDisabledFeatures(new[] { Feature }, context);
53            }
54            else
55            {
56                context.Result = new NotFoundResult();
57            }
58        }
59    }
60}

How it works

  1. Admin Bypass: The attribute first checks if the user is authenticated and has a claim named “platformadmin” with the value “true”. If so, the user is considered an administrator and is allowed to proceed, regardless of the feature flag state.
  2. Feature Flag Evaluation: If the user is not an admin, the attribute retrieves the IFeatureManager service and checks if the specified feature is enabled.
  3. Handling Disabled Features: If the feature is disabled, the attribute attempts to use an IDisabledFeaturesHandler to handle the situation (e.g., show a custom message or redirect). If no handler is available, it returns a 404 Not Found result.

Usage example

You can use the PlatformFeatureGateAttribute on controllers or actions:

C#
1[PlatformFeatureGate("NewDashboard")]
2public IActionResult Dashboard()
3{
4    return View();
5}

With this setup, administrators (users with the “platformadmin” claim) will always have access to the dashboard, while other users will only see it if the “NewDashboard” feature flag is enabled.

Conclusion

Customizing feature gates in ASP.NET Core gives you fine-grained control over feature access in your application. By leveraging claims-based authorization, you can ensure that administrators or other privileged users are never blocked by feature flags, while still maintaining flexibility for regular users.

This approach is especially useful in enterprise applications where business rules often require exceptions for certain user roles. With just a few lines of code, you can extend the default feature management system to fit your exact needs.

If you have any questions or want to see more advanced feature management scenarios, let me know in the comments!

Related articles

Production Rate Limiting in ASP.NET Core

Nov 3, 2026 - 16 min read

Production Rate Limiting in ASP.NET Core

Most ASP.NET Core rate-limiting examples stop after registering a fixed window. That is enough to demonstrate the middleware, but it is not …

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026 - 12 min read

Problem Details in ASP.NET Core and .NET 11

builder.Services.AddProblemDetails() registers infrastructure. It does not create an error contract. An ASP.NET Core request can fail during …

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026 - 11 min read

Resilience in .NET with Microsoft.Extensions.Resilience

Retries are the most visible resilience strategy and the easiest one to misuse. Repeating a failing call can recover from a short network …


BEN ABT

BEN ABT

Ben is Chief Engineering Officer and Principal Software Engineer at Medialesson.de, with a strong focus on .NET and Microsoft Azure. In his professional role, he designs and builds highly scalable platforms for hybrid and cloud-based scenarios. He also advises companies and C-levels on migrating to the sovereign cloud.

He runs myCSharp.de, the largest and most active German-speaking C# community forum, actively contributes to both his own and external open-source projects and regularly shares his knowledge through his blog, at community events, conferences and as a writer for technical magazines.

Let's Work Together

Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

New Platforms

Modernization

Training & Consulting

Contact Me
X Facebook LinkedIn WhatsApp
Back Next Blog Post

Open for work!

Contact Me
BEN ABT BEN ABT Software Engineer · Microsoft MVP Passionate about .NET, Azure, performance optimization and sustainable software engineering.

Medialesson GmbH Logo

Microsoft MVP Logo

Recent posts

View all
Production Rate Limiting in ASP.NET Core

Production Rate Limiting in ASP.NET Core

Nov 3, 2026
The Big Decimal Bugfix with .NET 11

The Big Decimal Bugfix with .NET 11

Nov 2, 2026
Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Oct 27, 2026
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026
Containerizing .NET in 2026 Without a Dockerfile

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026

Tags

.NET (195) Csharp (99) ASP.NET Core (49) Azure (41) DevOps (17) Docker (15) Microsoft (14) EF Core (11) Microsoft MVP (11) Security (11) AI (10) GitHub (10) GitHub Copilot (10) ASP.NET (9) Synology (9) .NET 11 (8) Architecture (8) Raspberry (8) Azure Functions (7) Cloudflare (7)
benjamin-abt.com

About BEN

Benjamin Abt is a Software Engineer, Platform Architect and Microsoft MVP specializing in .NET, Azure, cloud architecture, performance optimization and sustainable software development.

Connect

  • Follow me on GitHub
  • Follow me on LinkedIn
  • Follow me on Mastodon
  • Microsoft MVP profile
  • Follow SchwabenCode on GitHub
  • Follow me on X

Quick Links

  • Portfolio
  • Blog
  • Workshops & Training
  • Publications
  • Get in Touch
  • Sitemap
Open for Work

© Copyright Benjamin Abt & SchwabenCode | 2011 - 2026

Content licensed under CC BY 4.0 unless otherwise noted.

  • Impressum
  • Privacy
  • Contact