Filters and endpoint filters
Filters and endpoint filters
Filters apply cross-cutting behavior closer to a selected endpoint than ordinary middleware. MVC filters participate in the MVC action/result pipeline; Minimal API endpoint filters wrap handler invocation with access to bound arguments. Use a filter when behavior depends on a specific handler or result, not for every network request.
MVC has authorization, resource, action, exception and result filter stages; resource filters can surround model binding and the remaining invocation. Action filters run around controller actions. Page filters serve Razor Pages handler selection and execution; action filters are not a replacement for them. A filter may set a result to short-circuit an action. Minimal API filters receive EndpointFilterInvocationContext and a delegate for the next filter or handler; GetArgument<T> assumes a known bound argument position. They can reject semantic input before the handler, but do not generally catch failures before invocation, such as malformed JSON. Registration scope and order matter; for MVC global/controller/action scope and explicit Order influence ordering. Do not rely on an arbitrary filter as the only authorization boundary; use framework policies for access checks.
Baseline: .NET 10 / C# 14. Examples are independent Web SDK projects, with source files shown below or in the companion fixture. All expected outputs are reasoned, not executed. Run only in an isolated environment with an approved SDK, no real data, no launch profile and no external network. The finite loopback host uses ephemeral data protection keys and a test-only cookie container. No production security configuration is implied.
Add an MVC action filter
The selected controller action receives a response header from a filter before returning a result. An unrelated endpoint is unaffected.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddControllers();await using var app = builder.Build();app.MapControllers();app.MapGet("/other", () => "other");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var filtered = await client.GetAsync("/catalog", deadline.Token); using var other = await client.GetAsync("/other", deadline.Token); Check(filtered.IsSuccessStatusCode && filtered.Headers.GetValues("X-Lab-Action").Single() == "catalog", "MVC action filter"); Check(!other.Headers.Contains("X-Lab-Action"), "unrelated endpoint"); Console.WriteLine("MVC only");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}public sealed class CatalogHeaderAttribute : ActionFilterAttribute{ public override void OnActionExecuting(ActionExecutingContext context) { context.HttpContext.Response.Headers["X-Lab-Action"] = "catalog"; }}public sealed class CatalogController : ControllerBase{ [HttpGet("/catalog"), CatalogHeader] public IActionResult Get() => Ok("catalog");}Expected console observation (unexecuted):
MVC onlyThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Reject a bound quantity in an endpoint filter
The filter reads the already-bound int and rejects values outside the domain. A non-integer request fails binding separately.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/quote", (int quantity) => TypedResults.Ok(quantity * 3)) .AddEndpointFilter(async (invocation, next) => { int quantity = invocation.GetArgument<int>(0); if (quantity is < 1 or > 20) return Results.BadRequest("Quantity must be 1 to 20."); return await next(invocation); });using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var good = await client.GetAsync("/quote?quantity=4", deadline.Token); using var range = await client.GetAsync("/quote?quantity=0", deadline.Token); using var binding = await client.GetAsync("/quote?quantity=abc", deadline.Token); Check(good.IsSuccessStatusCode && (await good.Content.ReadAsStringAsync(deadline.Token)) == "12", "valid quantity"); Check(range.StatusCode == HttpStatusCode.BadRequest && binding.StatusCode == HttpStatusCode.BadRequest, "invalid inputs"); Console.WriteLine("12 / 400 / 400");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Expected console observation (unexecuted):
12 / 400 / 400The assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Wrap a route group with a filter
A group filter applies to its registered endpoints. This example rewrites string results before serialization, without modifying an already-started response.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();var group = app.MapGroup("/labels");group.AddEndpointFilter(async (invocation, next) =>{ var result = await next(invocation); return result is string text ? text.ToUpperInvariant() : result;});group.MapGet("/one", () => "map");group.MapGet("/two", () => "atlas");app.MapGet("/outside", () => "map");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; var one = await client.GetStringAsync("/labels/one", deadline.Token); var two = await client.GetStringAsync("/labels/two", deadline.Token); var outside = await client.GetStringAsync("/outside", deadline.Token); Check(one == "MAP" && two == "ATLAS" && outside == "map", "group scope"); Console.WriteLine($"{one} / {two} / {outside}");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Expected console observation (unexecuted):
MAP / ATLAS / mapThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Common mistakes and limitations
An MVC exception filter does not catch all middleware or result execution failures. Endpoint filters cannot be assumed to receive all malformed input. Avoid positional GetArgument calls on unknown handler signatures. Do not replace authorization policies with business validation filters.
Practice and recap
Choose a mechanism for request correlation IDs on all requests, validation of a quantity argument for one Minimal API, and behavior before an MVC action. Explain the scope of each.
Use the fixture assertions to verify the behavior after modification. Explain the observed result before moving to the next lesson.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Filters and endpoint filters — knowledge check
Apply the lesson concepts to the following scenarios.
Which filter wraps an MVC controller action?
What can GetArgument<int>(0) read?
What may happen before an endpoint filter runs?
Where should common request correlation run?
What does a group endpoint filter scope to?