liveBook · Manning

Endpoint filter

As explained in ASP.NET Core in Action, 3e

An endpoint filter is an ASP.NET Core component that runs processing around the execution of an associated endpoint and can alter or short-circuit its result.

An endpoint filter runs common processing around a minimal API endpoint without cluttering its handler. It can validate arguments, log results, perform other endpoint-specific work, or return a response before the handler runs. section 5.4

An endpoint filter works as a small pipeline:

  • Receives an EndpointFilterInvocationContext describing the selected endpoint and its arguments. section 5.4
  • Calls next(context) to continue through later filters and, eventually, the endpoint handler. section 5.4
  • Can execute code after the handler returns, or short-circuit by returning an IResult without calling next. section 5.4.1
  • Runs only for requests reaching the associated endpoint, unlike general middleware that can process all requests. section 5.4.2

Validate an endpoint argument

Attach a validation method with AddEndpointFilter(ValidationHelper.ValidateId). The method reads context.GetArgument<string>(0); when the identifier is missing or has the wrong format, it returns Results.ValidationProblem(...). Otherwise, it awaits next(context), allowing the handler to look up the fruit and return its result.

Generalize a filter with a factory

Use AddEndpointFilterFactory when handlers do not share the same parameter order. The factory inspects each endpoint’s signature, locates an id parameter, and creates a tailored filter; endpoints without id can receive no filter. section 5.4.3

Listing 5.10 Adding multiple filters to the endpoint filter pipeline
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
var _fruit = new ConcurrentDictionary<string, Fruit>();
 
app.MapGet("/fruit/{id}", (string id) =>
    _fruit.TryGetValue(id, out var fruit)
        ? TypedResults.Ok(fruit)
        : Results.Problem(statusCode: 404))
    .AddEndpointFilter(ValidationHelper.ValidateId)              #1
    .AddEndpointFilter(async (context, next) =>                  #2
    {
        app.Logger.LogInformation("Executing filter...");        #3
        object? result = await next(context);                    #4
        app.Logger.LogInformation($"Handler result: {result}");  #5
        return result;                                           #6
    });
 
app.Run();
#1 Adds the validation filter as before
#2 Adds a new filter using a lambda function
#3 Logs a message before executing the rest of the pipeline
#4 Executes the remainder of the pipeline and the endpoint handler
#5 Logs the result returned by the rest of the pipeline
#6 Returns the result unmodified

Review a complete endpoint pipeline that combines validation with a logging filter, showing valid requests continuing and invalid requests being rejected early. section 5.4.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains invocation context, pipeline ordering, short-circuiting, post-handler execution, and generalized filter factories.
Examples
Uses fruit API validation, result logging, multiple filters, and a factory handling different handler parameter orders.
What it assumes
Assumes minimal API endpoint handlers and basic middleware-pipeline ideas while teaching filter context, delegates, and argument access.
What you can do after
Apply it via AddEndpointFilter or AddEndpointFilterFactory to keep handlers focused and stop invalid requests before execution.
How it connects
Connects endpoint filters with minimal APIs, middleware, endpoint handlers, route groups, validation, logging, authorization, and auditing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.