
Endpoint Filters vs Middleware: Picking the Right Place for Cross-Cutting Logic
- كاتب موثّق
- .NET 10
محتويات المقال
POST /api/orders, it reads the JSON body, compares its customerId with the caller's claim, and answers 403 on a mismatch. Months later, a security review finds that PUT /api/orders/{id} accepts any customer id, and so does POST /api/orders/ with a trailing slash. Both requests reach real endpoints. Neither matches the string the middleware compares against, so the check never runs, and nothing fails to tell anyone.
The common misconception
next delegate, code before and after it, and an early return that skips the rest. The docs even describe filter order with the same nesting picture as the pipeline. Middleware is also the older tool: minimal APIs got endpoint filters only in .NET 7, so a lot of existing code does everything in middleware. And a path check or UseWhen seems to make any middleware endpoint-specific.
What actually happens
Two layers of one request
What each one can see
HttpContext: headers, the user, and, after routing, the route values and the endpoint's metadata. The body is only a stream. To inspect it, you enable buffering, deserialize it, rewind it, and let the endpoint deserialize it again. On the way out, the response is already bytes.
EndpointFilterInvocationContext.Arguments: the handler's arguments, already bound by and in declaration order, which it can read or replace. After next, it gets the handler's return value as an object, before serialization, and can return something else.
Who each one runs for
/api/orders/ as /api/orders; the string comparison didn't.
What filters never see
The ownership check, moved
ICustomerOwned interface with a CustomerId property, and MapOrders maps the order endpoints onto the group:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddJwtBearer();builder.Services.AddAuthorization();var app = builder.Build();app.UseAuthentication();app.Use(async (context, next) =>{ // Guards one exact string: other verbs and URL shapes skip it if (context.Request.Path == "/api/orders" && HttpMethods.IsPost(context.Request.Method)) { context.Request.EnableBuffering(); // parse now, parse again later var order = await context.Request.ReadFromJsonAsync<OrderRequest>(); context.Request.Body.Position = 0; if (order?.CustomerId != context.User.FindFirst("customer_id")?.Value) { context.Response.StatusCode = StatusCodes.Status403Forbidden; return; } } await next(context);});app.MapGroup("/api/orders").RequireAuthorization().MapOrders();app.Run();var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddJwtBearer();builder.Services.AddAuthorization();var app = builder.Build();app.MapGroup("/api/orders") .RequireAuthorization() .AddEndpointFilter<OwnCustomerOnly>() // every endpoint in the group .MapOrders();app.Run();public sealed class OwnCustomerOnly : IEndpointFilter{ public async ValueTask<object?> InvokeAsync( EndpointFilterInvocationContext context, EndpointFilterDelegate next) { var caller = context.HttpContext.User.FindFirst("customer_id")?.Value; // Arguments are already bound: no second parse of the body foreach (var owned in context.Arguments.OfType<ICustomerOwned>()) if (owned.CustomerId != caller) return TypedResults.Forbid(); return await next(context); }}POST /api/orders, then 201 to POST /api/orders/ and 200 to PUT /api/orders/5. A malformed body made ReadFromJsonAsync throw inside the middleware, so the client got a 500 instead of a 400. The filter version answered 403 to all three, and the malformed body got the framework's normal 400 without reaching the filter. The filter also never had to know which endpoints take an order: it checks any argument that implements the interface.
Middleware or filter?
HttpContext, the raw body stream, endpoint metadata after routing | ||
context.GetEndpoint()?.Metadata. That's how authorization works: the endpoint declares a policy, and middleware enforces it. Use that pattern when a rule must run in the pipeline but is declared per endpoint.
How to apply it in your project
Find middleware that matches URLs Search your middleware for Request.Path ==,StartsWithSegmentsandUseWhen. Each check that targets specific endpoints is a candidate for a filter, or for endpoint metadata.Keep app-wide plumbing in middleware Exception handling, HTTPS redirection, CORS, authentication, compression and request logging that must include 404s and malformed requests belong in the pipeline. Attach endpoint rules to groups Put filters on the route group so new endpoints inherit them, and describe what they check with an interface on the request types, so one filter serves many handlers. Test the shapes, not just the happy path Send the trailing-slash URL, the other verbs, a malformed body and a missing route value through the real app, and assert on the status code each one gets.
Key takeaways
Middleware wraps the whole app; an endpoint filter wraps one endpoint, or one group, after binding. Filters see typed arguments and the handler's result; middleware sees raw requests and response bytes. URL checks in middleware drift from routing; a filter on a group follows its endpoints, including new ones. 404s and unreadable bodies never reach filters, so logging and error handling stay in middleware.
التعليقات (0)