الانتقال إلى المحتوى
.NETMinimal APIs· 7 دقائق للقراءة

Endpoint Filters vs Middleware: Picking the Right Place for Cross-Cutting Logic

Middleware wraps every request before an endpoint is chosen; a filter wraps one endpoint after its arguments are bound. What each one sees, who it runs for, and where each check belongs.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

An orders API has a rule: customers can only place orders for themselves. A middleware enforces it. For 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

The belief: middleware and endpoint filters are two syntaxes for the same idea, so all logic can live in middleware. One place, runs for everything, nothing to forget.

It's a reasonable belief. Both have the same shape: a 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 the belief skips is where each one runs and what exists at that moment. That difference decides what each one can check reliably.

What actually happens

Two layers of one request

A request goes through the chain first. Routing picks an endpoint, more middleware runs, and then the endpoint executes. Inside the endpoint, the framework binds the handler's parameters, runs the filter pipeline (group filters, then the endpoint's own), calls the handler, and passes its return value back out through the filters before writing the response. Middleware is outside the endpoint; an is inside it. In a test, a filter on the route group ran first, then the endpoint's filter, then the handler.

What each one can see

Middleware sees the 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.

A filter gets 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

Middleware runs for every request that reaches it: static files, health checks, CORS preflights, URLs that match no endpoint. To target specific endpoints, it has to recognize URLs, and that's where the hook went wrong. Routing treated /api/orders/ as /api/orders; the string comparison didn't.

A filter is attached to an endpoint or a route group, so it follows the endpoint whatever its URL. A filter on a group runs for every endpoint in it, including endpoints added to the group later.

What filters never see

Filters run only once an endpoint is chosen, so 404s never reach them. They also don't run when reading the body fails, such as malformed JSON or an unsupported content type: the framework answers 400 first. Other binding failures, like a route value that doesn't parse, do run the filters, with the status code already set to 400 and the handler skipped.

The ownership check, moved

The request types implement a small ICustomerOwned interface with a CustomerId property, and MapOrders maps the order endpoints onto the group:

C# Program.cs
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();

Tested on .NET 10 with a caller "alice" sending orders for "bob". The middleware version answered 403 to 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?

MiddlewareEndpoint filter
Runs forEvery request that reaches it, matched or notOnly endpoints or groups it's attached to
Runs whenBefore and after routing, in registration orderAfter parameter binding, around the handler
SeesHttpContext, the raw body stream, endpoint metadata after routingThe same, plus bound arguments and the handler's return value
Targets endpoints byURL checks, or metadata the endpoint carriesBeing attached to them
Best forExceptions, HTTPS, CORS, authentication, compression, request loggingArgument rules, ownership checks, auditing, reshaping results

The middle ground is middleware that reads endpoint metadata after routing, with 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

  1. Find middleware that matches URLsSearch your middleware for Request.Path ==, StartsWithSegments and UseWhen. Each check that targets specific endpoints is a candidate for a filter, or for endpoint metadata.
  2. Keep app-wide plumbing in middlewareException handling, HTTPS redirection, CORS, authentication, compression and request logging that must include 404s and malformed requests belong in the pipeline.
  3. Attach endpoint rules to groupsPut 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.
  4. Test the shapes, not just the happy pathSend 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.

📚 المصادر

  1. Filters in Minimal API apps — Microsoft Learn
  2. ASP.NET Core middleware — Microsoft Learn
  3. Filters in ASP.NET Core — Microsoft Learn

التعليقات (0)