In an ASP.NET Core Minimal API, how do you write an IEndpointFilter that reads a handler argument and stops the request before the handler runs?
answer
- a wrapper around one handler
- ValueTask<object?> InvokeAsync(context, next)
- GetArgument<T>(index) and Arguments
- return a result without calling next
- AddEndpointFilter<T>: new instance per request
basics
~10 sImplement IEndpointFilter.InvokeAsync(EndpointFilterInvocationContext, EndpointFilterDelegate), read the bound value with context.GetArgument<T>(index), and return a result such as TypedResults.NotFound() without calling next to stop; otherwise return await next(context).
solid answer
~40 sAn endpoint filter implements `IEndpointFilter`, whose one method `InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)` returns `ValueTask<object?>`. The context exposes `HttpContext`, the already-bound handler arguments as `Arguments` (in declaration order) and `GetArgument<T>(index)` for a typed read. To stop the request, return a result such as `TypedResults.NotFound()` without calling `next`: the handler never runs and the returned object is written exactly as a handler's return value would be. To continue, `return await next(context)`, optionally inspecting or replacing what comes back. Register it with `AddEndpointFilter<KnownTruckFilter>()` on an endpoint or a group; that overload creates a new instance per request with `ActivatorUtilities` from `RequestServices`, so the constructor can take scoped services and the filter type is not registered in DI.
code
csharp · 18 linesapp.MapGet("/api/v1/fleet/trucks/{truckId:int}/position",
(int truckId, IFleetStore store) => store.GetPositionAsync(truckId))
.AddEndpointFilter<KnownTruckFilter>();
public sealed class KnownTruckFilter(IFleetStore store) : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var truckId = context.GetArgument<int>(0);
if (!await store.TruckExistsAsync(truckId, context.HttpContext.RequestAborted))
{
return TypedResults.NotFound();
}
return await next(context);
}
}go deeper
Recall the InvokeAsync signature, that GetArgument<T>(index) reads a bound handler parameter, and that returning a result without calling next stops the handler from running.
Explain the three registration overloads and their instance lifetimes, how a short-circuit result is written, and why a filter can replace an argument but not add one.
Spot the production traps: index coupling when handler signatures change, scoped services captured by a shared filter instance, and guards duplicated per endpoint that belong on a group.
Decide which rules live in filters at all: filters suit per-endpoint guards on bound data, while rules every request must pass belong earlier in the pipeline, and a team needs one convention for which is which.
## Where an endpoint filter sits An **endpoint filter** wraps a Minimal API handler. It runs after routing has picked the endpoint and after the handler's parameters have been bound, and before the handler is called; whatever it returns becomes the response. That makes it the place for logic that needs **bound, typed arguments** (a truck id parsed from the route, a deserialized request body, an injected service) rather than raw request data. The same filters can also be attached to controller actions through `app.MapControllers().AddEndpointFilter(...)`, but they are mostly met on Minimal API endpoints and groups. ## The contract - `IEndpointFilter.InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)` returns **`ValueTask<object?>`**. - `EndpointFilterDelegate` is the next filter, or the handler itself for the innermost filter. It has the same shape: it takes the context and returns `ValueTask<object?>`. - `context.HttpContext` gives the request, the response, the user and `RequestServices`. - `context.Arguments` is an `IList<object?>` holding every handler parameter in declaration order, injected services and special types included. You may replace an element by index and the handler receives the new value, but the list has a fixed size: `Add` throws `NotSupportedException`. - `context.GetArgument<T>(index)` is a typed read. It is a cast, so asking for the wrong `T` at a position throws `InvalidCastException`. ## A guard filter for the fleet tracker ```csharp public sealed class KnownTruckFilter(IFleetStore store) : IEndpointFilter { public async ValueTask<object?> InvokeAsync( EndpointFilterInvocationContext context, EndpointFilterDelegate next) { var truckId = context.GetArgument<int>(0); if (!await store.TruckExistsAsync(truckId, context.HttpContext.RequestAborted)) { return TypedResults.NotFound(); // the handler never runs } return await next(context); // continue to the handler } } ``` The filter reads the first argument as an `int`, asks a scoped store whether the truck exists and either short-circuits with a 404 or passes control on. ## Three ways to register a filter | Registration | Instance | Fits | |---|---|---| | `AddEndpointFilter(async (ctx, next) => ...)` | one lambda shared by every request | short, stateless checks | | `AddEndpointFilter(filterInstance)` | one object shared by every request on every endpoint it is attached to | thread-safe filters with singleton dependencies only | | `AddEndpointFilter<KnownTruckFilter>()` | a new object per request, built by `ActivatorUtilities` from `HttpContext.RequestServices` | filters with constructor dependencies, scoped ones included | The generic overload never asks the container for `KnownTruckFilter` itself; it constructs the type and resolves each constructor parameter from the request's services. Registering the filter type with `AddScoped` changes nothing. Its constructor may also accept an `EndpointFilterFactoryContext` to learn which handler it wraps. ## How the result is written 1. If the filter returns without calling `next`, the inner filters and the handler are skipped. 2. Whatever object reaches the top of the filter chain is written like a handler's return value: an `IResult` is executed, a `string` is written as `text/plain`, and any other object is serialized as JSON. 3. After `await next(context)` returns, the filter may inspect the result, wrap it or return a different one. ## Pitfalls - **Index coupling.** `GetArgument<int>(0)` breaks silently when someone reorders the handler's parameters; on a group, find the index per endpoint with `AddEndpointFilterFactory` instead. - **Calling `next` twice** runs the rest of the chain, handler included, twice. - **A shared instance with scoped state.** An object passed to `AddEndpointFilter(new ...)` lives as long as the app; giving it a scoped service captures one request's instance for all of them. - **Confusing it with MVC filters.** `IAsyncActionFilter` and `ActionExecutingContext.Result` belong to the MVC filter pipeline; an endpoint filter stops a request by what it returns. ## What interviewers listen for - The exact signature, `ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext, EndpointFilterDelegate)`, and that the arguments are already bound. - Short-circuiting by returning a result, not by setting a property or throwing. - The lifetime each registration overload gives the filter, and why the generic one can take scoped services. - A reason to prefer a filter here: it works on typed, bound arguments of the endpoints it is attached to, and nothing else.
- Can an endpoint filter change an argument before the handler sees it?Yes. The handler is invoked with values read back from the invocation context, so `context.Arguments[1] = normalized;` before `next` changes what the handler receives. The list is fixed-size, so you can replace but not add, and the new value must be of the parameter's type or the assignment fails with a cast error.
- Why does AddEndpointFilter<KnownTruckFilter>() work without registering KnownTruckFilter in DI?The overload builds an `ObjectFactory` with `ActivatorUtilities.CreateFactory` and, on each request, calls it with `HttpContext.RequestServices`. That constructs the filter type directly and resolves only its constructor parameters from the container, so a registration for the filter type is never consulted and each request gets a fresh instance.
- Can the same endpoint filter be used on MVC controller actions?Yes, through the controller endpoint conventions: `app.MapControllers().AddEndpointFilter<ControllerActionEndpointConventionBuilder, KnownTruckFilter>()` (the one-type-argument shortcut exists only for route handler and group builders). The filter then receives the action's arguments in its invocation context. MVC's own action filters, such as `IAsyncActionFilter`, remain a separate pipeline with separate ordering rules.
- IEndpointFilter.InvokeAsync returns Task, like IMiddleware.InvokeAsync.
- An endpoint filter stops the request by setting context.Result, as an MVC action filter does.
- AddEndpointFilter<T>() resolves the filter from DI, so it must be registered with AddScoped first.
- Filters see only raw strings because handler arguments are bound after the filters run.
- An object passed to AddEndpointFilter(new X()) is created fresh for every request.