AddEndpointFilter attaches an endpoint filter to a minimal API endpoint or route group. Filters keep cross-cutting code such as validation, logging, authorization, or auditing out of endpoint handlers. section 5.4 section 5.6
Use the filter pipeline to control work before and after an endpoint handler:
- Receive an EndpointFilterInvocationContext containing details about the selected handler. section 5.4
- Read handler arguments with context.GetArgument<T>(), using zero for the first argument, one for the second, and so on. section 5.4
- Return an IResult immediately when validation fails, or call await next(context) to continue through remaining filters and eventually invoke the handler. section 5.4
- Call AddEndpointFilter multiple times to build a pipeline, or attach one filter to every endpoint in a route group. section 5.6 section 5.5
Extracting ID validation
app.MapGet("/fruit/{id}", (string id) => _fruit.TryGetValue(id, out var fruit) ? TypedResults.Ok(fruit) : Results.Problem(statusCode: 404)) .AddEndpointFilter(ValidationHelper.ValidateId); The filter reads argument 0, returns Results.ValidationProblem for an empty or incorrectly formatted ID, and calls await next(context) for valid input. section 5.4
