Coding question on Minimal API endpoint filters: IEndpointFilter and inline AddEndpointFilter, EndpointFilterInvocationContext and argument access, short-circuiting with a result, applying filters to route groups, onion ordering of group and endpoint filters, filter factories, and when to use endpoint filters versus middleware or .NET 10 built-in validation.
An endpoint filter is the Minimal API equivalent of an MVC action filter: it wraps the handler invocation after routing and parameter binding, so it can see the bound arguments through EndpointFilterInvocationContext.Arguments, run code before and after the handler, change the result, or short-circuit by returning a result without calling next. You implement IEndpointFilter (or pass a lambda to AddEndpointFilter) and attach it to an endpoint or a route group. Order is an onion: filters run in the order added on the way in and reverse on the way out, with group filters outside endpoint filters. AddEndpointFilterFactory lets you inspect the handler once at start-up and skip the filter where it isn't needed. The trade-off: filters are precise and cheap but only wrap Minimal API handlers; global concerns stay in middleware.
> "Endpoint filters came in .NET 7 to give Minimal APIs what action filters give controllers. Routing has already chosen the endpoint and binding has already produced the arguments, so a filter gets an EndpointFilterInvocationContext with the HttpContext and the Arguments list, plus a next delegate. It can inspect or replace arguments, call next to run the handler, and look at or replace the result. If it returns a result without calling next, the handler never runs, which is how a validation or feature-flag filter short-circuits.
>
> I write them as classes implementing IEndpointFilter so they get constructor injection and can be unit tested, and I attach them to a route group so a whole feature gets them, including endpoints added later. Ordering is an onion: the first filter added is outermost. Group filters wrap endpoint filters, and nested groups wrap inner ones. For generic filters I like AddEndpointFilterFactory: it runs once at start-up with the handler's MethodInfo, so a validation filter can find which argument position holds the DTO and return next unchanged for endpoints that don't need it, which costs nothing per request.
>
> The mistake I see is using filters for things that should apply to every request, like correlation IDs. Filters only run for matched Minimal API endpoints, not for 404s, static files or controllers. And in .NET 10, I don't write a DataAnnotations validation filter any more because AddValidation() does it; filters are for FluentValidation, idempotency keys, auditing and similar handler-aware concerns."
| Action | How |
|---|---|
| Read arguments | `context.GetArgument |
Checks practical Minimal API skills: writing a correct, reusable filter and understanding where it runs.
Green flags
Red flags
GetArgument<T>(0) in a generic filter.AddValidation().Routing ─► Endpoint RequestDelegate
├─ bind parameters (route, query, body, services)
├─ build EndpointFilterInvocationContext(arguments)
├─ filter 1 ─► filter 2 ─► ... ─► handler
└─ write result (IResult.ExecuteAsync or JSON)
Binding failures (400) happen before filters, so a filter never sees an unbindable request.
When the endpoint is built, the RequestDelegateFactory composes all filters into one EndpointFilterDelegate. Each AddEndpointFilter registers an EndpointFilterFactory delegate in the endpoint's builder conventions. Factories run once at start-up with an EndpointFilterFactoryContext exposing MethodInfo and services, and return the per-request delegate.
EndpointFilterInvocationContext.Arguments is an IList<object?> in handler parameter order. Generic DefaultEndpointFilterInvocationContext<T1..Tn> avoids boxing in generated code; GetArgument<T> reads typed values. Services and CancellationToken are arguments too.
next returns object?: either an IResult or the handler's raw return value (which will be JSON-serialised). Filters that wrap results must handle both.
AddEndpointFilter<TFilter>() creates the filter with ActivatorUtilities per request using request services, so scoped dependencies are fine. Inline lambdas are simplest but harder to test.
AddValidation() itself is implemented as an endpoint filter added by convention. Calling .DisableValidation() on an endpoint removes it.
WebApplicationFactory.AddEndpointFilterFactory to attach a FluentValidation filter only to handlers that have a parameter with a registered IValidator<T>.IEndpointFilter by constructing DefaultEndpointFilterInvocationContext directly.A reusable FluentValidation endpoint filter built with a factory so it only runs where a validator exists, plus an idempotency filter on a route group.
// Filters/ValidationFilterFactory.cs
using System.Reflection;
using FluentValidation;
namespace Payments.Api.Filters;
public static class ValidationFilterFactory
{
// Runs ONCE per endpoint at start-up: find which argument needs validating
public static EndpointFilterDelegate Create(EndpointFilterFactoryContext factoryContext, EndpointFilterDelegate next)
{
var parameters = factoryContext.MethodInfo.GetParameters();
var services = factoryContext.ApplicationServices;
var targets = parameters
.Select((p, index) => (Index: index, ValidatorType: typeof(IValidator<>).MakeGenericType(p.ParameterType)))
.Where(t => services.GetService(typeof(IServiceProviderIsService)) is IServiceProviderIsService isService
&& isService.IsService(t.ValidatorType))
.ToArray();
if (targets.Length == 0) return next; // nothing to validate: zero per-request cost
return async invocation =>
{
foreach (var (index, validatorType) in targets)
{
var validator = (IValidator)invocation.HttpContext.RequestServices.GetRequiredService(validatorType);
var argument = invocation.Arguments[index];
if (argument is null) continue;
var result = await validator.ValidateAsync(new ValidationContext<object>(argument),
invocation.HttpContext.RequestAborted);
if (!result.IsValid) return TypedResults.ValidationProblem(result.ToDictionary()); // short-circuit
}
return await next(invocation);
};
}
}
// Idempotency: repeated keys get the original outcome instead of a second charge
public sealed class IdempotencyFilter(IIdempotencyStore store) : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var key = context.HttpContext.Request.Headers["Idempotency-Key"].ToString();
if (string.IsNullOrWhiteSpace(key))
return TypedResults.Problem("Idempotency-Key header is required.", statusCode: StatusCodes.Status400BadRequest);
if (await store.TryGetAsync(key, context.HttpContext.RequestAborted) is { } previous)
return TypedResults.Ok(previous);
var result = await next(context);
await store.SaveAsync(key, result, context.HttpContext.RequestAborted);
return result;
}
}
public interface IIdempotencyStore
{
Task<object?> TryGetAsync(string key, CancellationToken ct);
Task SaveAsync(string key, object? result, CancellationToken ct);
}
// Program.cs
using FluentValidation;
using Payments.Api.Filters;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IValidator<CreatePayment>, CreatePaymentValidator>();
builder.Services.AddSingleton<IIdempotencyStore, RedisIdempotencyStore>();
var app = builder.Build();
var payments = app.MapGroup("/payments")
.AddEndpointFilter<IdempotencyFilter>() // outermost: runs first, sees final result last
.AddEndpointFilterFactory(ValidationFilterFactory.Create);
payments.MapPost("/", (CreatePayment cmd) => TypedResults.Ok(new { Id = Guid.NewGuid(), cmd.AmountCents }));
app.Run();
public sealed record CreatePayment(string AccountId, long AmountCents);
public sealed class CreatePaymentValidator : AbstractValidator<CreatePayment>
{
public CreatePaymentValidator()
{
RuleFor(x => x.AccountId).NotEmpty();
RuleFor(x => x.AmountCents).InclusiveBetween(1, 10_000_000);
}
}
AddValidation() already validates DataAnnotations (nested objects and collections included) with source generation and a standard ProblemDetails 400, so a custom filter duplicates it and can drift in error shape. Instead: Use the built-in validation; DataAnnotations themselves remain the right tool. Write a custom filter when you need FluentValidation, rules DataAnnotations can't express, a different error contract, or you target .NET 8/9.MethodInfo, or search by type.next returns an IResult. Why it is wrong: It returns the handler's raw value when the handler returns a DTO. Instead: Handle both IResult and plain objects when wrapping results.AddEndpointFilterFactory, cache lookups, and measure with a load test if the filter sits on a hot path.Endpoint filters are the right place for concerns that depend on the handler: its arguments, its result, or its metadata. The factory form is the senior touch: decide at start-up whether a filter applies, so endpoints that don't need it pay nothing. Keep the global pipeline in middleware and lean on built-in features (validation, output caching, rate limiting, auth policies) before writing a filter.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
IEndpointFilter class |
Reusable, testable handler-aware logic | One class | Trivial one-offs |
| Inline lambda filter | Small, endpoint-specific logic | Hard to test | Shared behaviour |
AddEndpointFilterFactory |
Generic filters that depend on handler signature | Reflection at start-up | Simple filters |
| Middleware | Every request | No access to arguments | Handler-specific logic |
Built-in (AddValidation, CacheOutput, RequireRateLimiting) |
Common needs | None | When you need custom behaviour |
MVC filters run inside the MVC action invoker, around specific stages of an action. Authorisation filters run first and can short-circuit; resource filters wrap model binding and everything after, so they suit caching or rejecting early; action filters run just before and after the action and can see and change the bound arguments and result; exception filters handle exceptions from the action and action filters; result filters wrap the execution of the result, e.g. adding headers. Ordering is by scope (global → controller → action on the way in, reversed on the way out) unless Order says otherwise. I use a filter instead of middleware when the logic needs MVC context: the action, its arguments or ModelState. Middleware is for things true of every request. The trade-off: filters are precise but MVC-only.
I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.
Last updated 23 Nov 2026.