How does IEndpointFilter provide similar cross-cutting functionality for minimal APIs that MVC filters provide for controllers?
Short answer
IEndpointFilter.InvokeAsync(EndpointFilterInvocationContext, EndpointFilterDelegate) wraps a minimal API endpoint's execution, letting you inspect/modify arguments before invocation and the result after, applied via .AddEndpointFilter() on individual endpoints or entire route…
Advertisement
AModel answer
IEndpointFilter.InvokeAsync(EndpointFilterInvocationContext, EndpointFilterDelegate) wraps a minimal API endpoint's execution, letting you inspect/modify arguments before invocation and the result after, applied via .AddEndpointFilter() on individual endpoints or entire route groups -- serving a conceptually similar role to MVC's IAsyncActionFilter but designed specifically for minimal API's lighter-weight style.
public class ValidationFilter<T> : IEndpointFilter {
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) {
var arg = context.GetArgument<T>(0);
if (!IsValid(arg)) return Results.BadRequest("Invalid input");
return await next(context);
}
}
app.MapPost("/products", Create).AddEndpointFilter<ValidationFilter<ProductDto>>();Real-world example
A minimal-API-based project implements one reusable generic ValidationFilter<T> applied across many endpoints accepting different DTOs, replicating [ApiController]'s automatic validation behavior consistently without per-endpoint duplication.
Likely follow-ups
- How does IEndpointFilter's context.GetArgument access typed parameters compared to MVC's ActionArguments dictionary?
- Can the same filter logic be shared between MVC action filters and minimal API endpoint filters?
Related topics