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
