Filters
Middleware runs for every request. Sometimes you want logic that runs only around particular endpoints or controller actions — timing an action, validating an argument, adding a header to some responses, or turning an exception into a nice result. That is what filters are for.
ASP.NET Core 9 has two families:
| Family | Used with | Main interface |
|---|---|---|
| Endpoint filters | Minimal APIs (MapGet, MapPost, route groups) |
IEndpointFilter |
| MVC filters | Controllers and Razor Pages | IActionFilter, IExceptionFilter, IResultFilter, … |
Both work the same way at heart: a filter receives the call, can do work before it, decides whether to call next, and can inspect or replace the result after it.
Endpoint filters for minimal APIs
An endpoint filter gets an EndpointFilterInvocationContext (which holds the HttpContext and the handler's arguments) and a next delegate:
app.MapPost("/todos", (TodoInput input) =>
Results.Created(quot;/todos/1", new { id = 1, input.Title }))
.AddEndpointFilter(async (context, next) =>
{
var input = context.GetArgument<TodoInput>(0);
if (string.IsNullOrWhiteSpace(input.Title))
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["title"] = ["Title is required."]
});
}
return await next(context); // run the handler
});
record TodoInput(string Title);If the title is blank, the handler never runs:
$ curl -s -X POST localhost:5000/todos -H "Content-Type: application/json" -d '{"title":""}'
$ curl -s -X POST localhost:5000/todos -H "Content-Type: application/json" -d '{"title":"Read docs"}'{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"title":["Title is required."]}}
{"id":1,"title":"Read docs"}
Filters can also be classes, which makes them reusable and lets them take services through the constructor:
public sealed class TimingFilter(ILogger<TimingFilter> logger) : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var start = Stopwatch.GetTimestamp();
var result = await next(context);
logger.LogInformation("{Path} took {Ms} ms",
context.HttpContext.Request.Path, Stopwatch.GetElapsedTime(start).TotalMilliseconds);
return result;
}
}
// Apply to every endpoint in a group
var todos = app.MapGroup("/todos").AddEndpointFilter<TimingFilter>();Tip: Filters added to a route group apply to all endpoints in that group, so a group is a neat way to say "all of these need the same checks".
How a filter chain works
Several filters wrap each other like layers of an onion: the first filter added is the outermost. This plain-C# program builds the same kind of chain from delegates:
using System;
using System.Collections.Generic;
Func<string, string> handler = title => quot;Created '{title}'";
var filters = new List<Func<string, Func<string, string>, string>>
{
(arg, next) => { Console.WriteLine("logging: before"); var r = next(arg); Console.WriteLine("logging: after"); return r; },
(arg, next) => string.IsNullOrWhiteSpace(arg) ? "400 Title is required" : next(arg),
(arg, next) => next(arg.Trim()),
};
// Wrap from the last filter to the first so the first one ends up outermost
Func<string, string> pipeline = handler;
for (int i = filters.Count - 1; i >= 0; i--)
{
var filter = filters[i];
var next = pipeline;
pipeline = arg => filter(arg, next);
}
Console.WriteLine(pipeline(" Read docs "));
Console.WriteLine(pipeline(" "));logging: before
logging: after
Created 'Read docs'
logging: before
logging: after
400 Title is required
The validation filter short-circuits: for a blank title it returns without calling next, so the trimming filter and the handler never run — but the logging filter, being outside it, still sees the call.
MVC filters
Controllers have a richer pipeline with several filter kinds, each running at a specific stage:
| Order | Filter | Typical use |
|---|---|---|
| 1 | Authorization (IAuthorizationFilter) |
Reject unauthenticated or forbidden requests |
| 2 | Resource (IResourceFilter) |
Caching, short-circuit before model binding |
| 3 | Action (IActionFilter) |
Inspect/modify arguments before, result after the action |
| 4 | Exception (IExceptionFilter) |
Turn exceptions thrown by actions into results |
| 5 | Result (IResultFilter) |
Run around the execution of the action result, e.g. add headers |
An action filter written as an attribute:
public sealed class RequireApiVersionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.HttpContext.Request.Headers.ContainsKey("X-Api-Version"))
{
context.Result = new BadRequestObjectResult(new { error = "X-Api-Version header missing" });
}
}
public override void OnActionExecuted(ActionExecutedContext context)
{
context.HttpContext.Response.Headers["X-Handled-By"] = context.ActionDescriptor.DisplayName;
}
}
[ApiController]
[Route("api/[controller]")]
public class ReportsController : ControllerBase
{
[HttpGet, RequireApiVersion]
public IActionResult Get() => Ok(new[] { "q1", "q2" });
}Setting context.Result in OnActionExecuting short-circuits: the action method is not called.
$ curl -s localhost:5000/api/reports
$ curl -s localhost:5000/api/reports -H "X-Api-Version: 1"{"error":"X-Api-Version header missing"}
["q1","q2"]
Where to register a filter
| Scope | How |
|---|---|
| One action / controller | Put the attribute on the method or class |
| All controllers | builder.Services.AddControllers(o => o.Filters.Add<MyFilter>()); |
| Filter that needs DI services | [ServiceFilter(typeof(MyFilter))] (registered in DI) or [TypeFilter(typeof(MyFilter))] |
| Minimal API endpoint or group | .AddEndpointFilter(...) |
Filters or middleware?
Use middleware for cross-cutting concerns that apply to every request and do not care which endpoint was chosen (compression, HTTPS redirection, request logging). Use filters when you need endpoint-level information — the action's arguments, its attributes, or its result object — or when the behaviour should apply only to some endpoints.
Test yourself
In an endpoint filter, how do you stop the handler from running?
- Throw a FilterException
- Return a result without calling
next - Set
context.Cancel = true - Call
nexttwice
Which MVC filter type runs first for a controller action?
- Action filter
- Result filter
- Exception filter
- Authorization filter
If filters A, B and C are added to an endpoint in that order, which one runs its 'before' code first?
- A
- B
- C
- The order is random