Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 52 ยท Routing and Minimal APIs

Endpoint Filters

Wrap minimal API handlers with endpoint filters: AddEndpointFilter, IEndpointFilter classes, short-circuiting, validation filters and execution order.

Sooner or later several endpoints need the same extra step: check that a request body is valid, log the arguments, reject a missing header, wrap a result in a standard envelope. Copying that code into every handler is error-prone, and middleware is too blunt, because it runs for every request and knows nothing about which endpoint was chosen or what its parameters are. Endpoint filters fill the gap. They run around a single endpoint's handler, after routing and after parameter binding, and they can see (and change) both the bound arguments and the result.

You will learn the filter signature, how to write one inline and as a class, how a filter short-circuits the pipeline, how to build a reusable validation filter, and in which order several filters run. If minimal API handlers are new to you, read Minimal API Endpoints and Parameter Binding first.

Where filters sit

Think of the handler as the center of an onion. Middleware wraps the whole app; endpoint filters wrap one endpoint and run closer to the handler.

flowchart LR
    R["Request"] --> M["Middleware<br/>(all requests)"]
    M --> RT["Routing<br/>picks the endpoint"]
    RT --> B["Parameter<br/>binding"]
    B --> F1["Filter 1"]
    F1 --> F2["Filter 2"]
    F2 --> H["Handler"]
    H -.-> F2
    F2 -.-> F1

Filters run after routing and binding, in registration order on the way in, and in reverse on the way out. Any filter can stop the chain instead of calling the next one.

Because binding is finished by then, a filter does not parse the request. It receives the already-bound arguments and the HttpContext.

The shape of a filter

A filter is a function from an EndpointFilterInvocationContext and a next delegate to a ValueTask<object?>:

C#
async ValueTask<object?> (EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
    // before the handler
    object? result = await next(context);   // call the rest of the chain
    // after the handler
    return result;
}

The context offers context.HttpContext, context.Arguments (the list of bound handler arguments) and context.GetArgument<T>(index). What you return becomes the result of the endpoint, exactly like a handler's return value, so you may return Results.* helpers, plain objects or whatever next gave you.

C# An inline filter that logs arguments and result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The filter saw the two integers that binding had already parsed, and it saw the handler's raw return value (42, still an int) before it was written to the response. A filter could also replace that value: return (int)result! * 2; would double it.

Short-circuiting: stop before the handler

If a filter does not call next, the handler (and all inner filters) never run. Whatever the filter returns is the response. This is the basis of validation, authorization-like checks and caching.

C# A filter that short-circuits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Only two of the three requests reached the handler. The rejected one was answered by the filter, and the 75 never touched your business code.

Filters as classes

An inline lambda is fine for one endpoint. A rule you reuse deserves a class that implements IEndpointFilter, because it can take services through its constructor and has a name. Register it with AddEndpointFilter<TFilter>(); the filter is created once when the endpoint is built, and its constructor parameters come from the dependency injection container.

Here is the most common reusable filter, a validation filter. It finds an argument of type T, runs a validation function and returns a standard 400 with a list of errors.

C# A reusable validation filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The filter is generic, so AddEndpointFilter<ValidationFilter<SignUp>>() plugs in the right validator, found through DI. The same filter class can protect PUT /profile with ValidationFilter<Profile>. The next lessons take the idea further: Model Validation covers data annotations and the built-in validation support.

Filters created with AddEndpointFilter<T>() are resolved when the endpoint is built, not per request, so do not inject scoped services into the constructor. If a filter needs a scoped service, ask for it at call time with context.HttpContext.RequestServices.

Order of execution

Filters run in the order you add them, like middleware: the first is the outermost. Filters added on a route group wrap the filters added on the individual endpoint, so group-level filters always run first on the way in and last on the way out.

C# Group and endpoint filter order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The trace reads group filter: in, A: in, B: in, handler, then B: out, A: out, group filter: out. Keep the order in mind when you write filters that depend on each other: a filter that normalizes input must be added before the filter that validates it.

Filters versus middleware

Middleware Endpoint filter
Runs for every request one endpoint or one group
Knows the endpoint's arguments no yes (context.Arguments)
Runs when before routing (or after, depending on position) after routing and binding
Can see the handler's return value only after it is written before it is written, as an object
Typical use logging, error handling, compression, authentication validation, per-endpoint rules, result shaping

A good rule: if the logic is about the HTTP request as a whole, use middleware. If it is about this endpoint's inputs or outputs, use a filter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. At what point in request processing does an endpoint filter run?

    Endpoint filters wrap a single endpoint's handler. They run after routing selected the endpoint and after its parameters were bound, which is why they can read context.Arguments.
  2. 2. What happens if a filter returns Results.BadRequest() without calling next(context)?

    Not calling next short-circuits the chain. The value the filter returns becomes the endpoint's result.
  3. 3. Group filter G, then endpoint filters A and B (added in that order) wrap a handler. In which order do they start running?

    Filters run in registration order on the way in, and group filters wrap endpoint filters, so the order is G, A, B, handler and then B, A, G on the way out.
  4. 4. Why should a filter registered with AddEndpointFilter<T>() avoid constructor-injecting scoped services?

    The filter instance is created while building the endpoint, not per request. Resolve scoped services at call time from context.HttpContext.RequestServices instead.

Summary

  • An endpoint filter is ValueTask<object?> (EndpointFilterInvocationContext context, EndpointFilterDelegate next); add it with AddEndpointFilter on an endpoint or a group.
  • Filters run after routing and binding and see the bound arguments through context.Arguments and GetArgument<T>.
  • Calling next(context) continues the chain; returning without it short-circuits and your return value becomes the response.
  • Implement IEndpointFilter for reusable, DI-friendly filters such as a generic validation filter.
  • Execution order is registration order, group filters outermost; the way out is the reverse.
  • Use middleware for request-wide concerns and filters for per-endpoint concerns.

Next: The Middleware Pipeline