Advertisement
Advanced .NET, ASP.NET Core Middleware & Request Pipeline

How do minimal API endpoint filters (IEndpointFilter) compare to traditional middleware for cross-cutting logic?

Short answer

Endpoint filters, introduced for minimal APIs, apply cross-cutting logic (validation, logging, authorization checks) at the granularity of individual endpoints or route groups rather than the entire pipeline, and get typed access to the endpoint's actual arguments via…

Save .NET mock interview
Advertisement
AModel answer
Endpoint filters, introduced for minimal APIs, apply cross-cutting logic (validation, logging, authorization checks) at the granularity of individual endpoints or route groups rather than the entire pipeline, and get typed access to the endpoint's actual arguments via EndpointFilterInvocationContext -- offering finer control than pipeline-wide middleware while being lighter weight than writing a full middleware class for endpoint-specific concerns.
app.MapGet("/products/{id}", (int id) => GetProduct(id))
   .AddEndpointFilter(async (context, next) => {
       var id = context.GetArgument<int>(0);
       if (id <= 0) return Results.BadRequest("Invalid id");
       return await next(context);
   });
Real-world example
A minimal API validates route parameters using an endpoint filter applied only to specific endpoints that need it, rather than writing pipeline-wide middleware that would need to parse and re-validate arguments for every route indiscriminately.
Likely follow-ups
  • How do endpoint filters access strongly-typed endpoint arguments?
  • Can endpoint filters be reused as a filter factory across many endpoints?
Related topics