With MediatR in an ASP.NET Core API, how does an IPipelineBehavior differ from middleware and a Minimal API endpoint filter, and when do you choose each?
answer
- HttpContext vs bound arguments vs typed request
- middleware: every HTTP request
- endpoint filter: one endpoint or group
- behaviour: every Send, any caller
- returns TResponse, not an IResult
basics
~20 sMiddleware sees every HTTP request as an HttpContext; an endpoint filter wraps chosen endpoints and sees bound arguments; a MediatR behaviour wraps each Send with the typed request, whoever sends it. Choose by what the concern must see and who calls.
solid answer
~50 sThe three run at different layers of one request. **Middleware** (`RequestDelegate`, `IMiddleware`) runs for every HTTP request in pipeline order and knows only `HttpContext`: the place for authentication, CORS, compression and request logging. An **endpoint filter** (`IEndpointFilter.InvokeAsync(EndpointFilterInvocationContext, EndpointFilterDelegate)`) runs only for the endpoints or group it is added to, after binding, sees `context.Arguments` and can return an `IResult`: the place for HTTP-shaped checks on one route. A **MediatR behaviour** runs inside `ISender.Send`, sees the typed command and its `TResponse`, and runs whether the sender is an endpoint, a background job or a message consumer, but it cannot produce an HTTP result for an arbitrary request. So: HTTP-wide concerns in middleware, route-specific HTTP concerns in filters, command-level rules such as validation, transactions and auditing in behaviours. Also note that a nested `Send` passes through the behaviours again.
code
csharp · 11 linespublic sealed class IdempotencyKeyFilter : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context,
EndpointFilterDelegate next)
{
if (!context.HttpContext.Request.Headers.ContainsKey("Idempotency-Key"))
return TypedResults.BadRequest("Idempotency-Key header is required.");
return await next(context);
}
}go deeper
Recall the three layers: middleware for every HTTP request, endpoint filters for specific endpoints, and MediatR behaviours for every Send of a request.
Explain what each layer sees and returns, HttpContext, bound arguments or the typed request, and why only behaviours run for non-HTTP callers.
Assign concerns deliberately: HTTP in middleware or filters, command rules in behaviours, one owner per rule, and behaviours that tolerate nested Send calls.
Set the convention for the codebase: which cross-cutting concerns live at which layer, so teams stop duplicating rules and reviewers know where to look.
## Three pipelines, one request A `POST /leases/{id}/payments` in the property-management API passes through three separate pipelines, each built from its own kind of component: 1. **Middleware**: `UseExceptionHandler`, `UseAuthentication`, `UseAuthorization` and your own `RequestDelegate` classes, in the order `Program.cs` adds them. 2. **Endpoint filters**: those attached with `AddEndpointFilter` to this endpoint or its route group, wrapped around the route handler after parameter binding. 3. **The route handler**, which calls `sender.Send(new RecordRentPayment(...))`, and inside it the **MediatR behaviours** wrapped around the request handler. Each layer can run code before and after the next one and can stop the request early. What differs is what each one can see, who it applies to, and what it can return. ## Side by side | | Middleware | Endpoint filter | MediatR behaviour | |---|---|---|---| | Interface | `RequestDelegate`, `IMiddleware` | `IEndpointFilter` | `IPipelineBehavior<TRequest, TResponse>` | | Applies to | every HTTP request reaching it | endpoints or groups it is added to | every `Send` of matching request types | | Sees | `HttpContext` (raw request) | `EndpointFilterInvocationContext.Arguments` (bound values) and `HttpContext` | the typed request object | | Can return | writes the HTTP response | any value, typically an `IResult` | a `TResponse` (or throws) | | Runs for non-HTTP callers | no | no | yes: jobs, consumers, other handlers | | Registered | `app.Use...` order in `Program.cs` | `.AddEndpointFilter<T>()` on the route | `cfg.AddOpenBehavior(...)` order | ## Choosing - **Concern exists because of HTTP** (authentication, CORS, compression, correlation headers, HTTP request logging): middleware. It sees everything, including requests that match no endpoint. - **Concern is about one route's HTTP contract** (an idempotency-key header on payment endpoints, rejecting a malformed argument with a 400): an endpoint filter. It sees bound arguments and can return `TypedResults.ValidationProblem` or `TypedResults.Conflict` directly. - **Concern is about the command itself and must hold no matter who sends it** (validating `RecordRentPayment`, wrapping it in a transaction, auditing who changed a lease, timing each command): a MediatR behaviour. The nightly job that sends `RecordLateFee` gets exactly the same rules as the API. ## Traps when mixing them 1. **Double work.** Validating the same rules in an endpoint filter and a validation behaviour runs them twice and lets them drift apart. Give each rule one owner. 2. **HTTP leaking inward.** A behaviour that reads `IHttpContextAccessor` to decide something breaks when a job sends the command, because there is no request. 3. **Results don't fit.** A behaviour must return `TResponse`; it cannot return an `IResult` for a request whose response is a `PaymentReceipt`. Throw, and let the edge map the exception. 4. **Nested sends.** A handler that sends another command runs every behaviour again, nested; middleware and filters ran only once for the HTTP request. Logging and transaction behaviours must expect that. 5. **Ordering is per pipeline.** Middleware order, filter order and behaviour order are three separate lists; there is no single place that orders a behaviour relative to a filter. Filters always run before the handler calls `Send`. ## A layout that holds up ```csharp app.UseAuthentication(); app.UseAuthorization(); app.MapGroup("/leases") .RequireAuthorization() .AddEndpointFilter<IdempotencyKeyFilter>() .MapPost("/{id:guid}/payments", async (Guid id, PaymentInput input, ISender sender, CancellationToken ct) => TypedResults.Ok(await sender.Send(new RecordRentPayment(id, input.Amount), ct))); // AddMediatR: AddOpenBehavior(Logging), AddOpenBehavior(Validation), AddOpenBehavior(Transaction) ``` ## Questions that decide the layer 1. Does the concern need anything from HTTP (headers, route, user claims as presented by the request)? If yes, middleware or a filter. 2. Does it apply to all routes or to some? All: middleware. Some: a filter on the endpoint or group. 3. Must it hold when the same command is sent by a job, a consumer or another handler? If yes, a behaviour. 4. Does it need to return an HTTP result? Behaviours cannot, for an arbitrary request. Authentication and authorization stay in middleware and endpoint metadata; the idempotency key, an HTTP header, is checked by a filter on the group; validation and the transaction travel with the command into every caller.
- Why does a MediatR logging behaviour log twice for one HTTP request when RenewLease sends RecordRentPayment?Behaviours wrap every `Send`, and the nested `Send` from inside the `RenewLease` handler is a second trip through the whole pipeline, so the logging behaviour runs once for each command. Middleware and endpoint filters ran only once, for the HTTP request. Usually that is correct, but transaction and audit behaviours must be written to expect nesting.
- Can a MediatR behaviour return a 400 response the way an endpoint filter can?Not in general. A behaviour must return the request's `TResponse`, such as a `PaymentReceipt`, so it cannot return an `IResult`; it can only throw, or return a failure value if `TResponse` is a result type of your own. An endpoint filter returns `ValueTask<object?>` and can return `TypedResults.BadRequest` directly.
- A MediatR behaviour runs for every HTTP request, like middleware.
- Endpoint filters also run when a background job sends the command.
- A behaviour can return TypedResults.BadRequest for any request type.
- Middleware can read the typed command object that the handler receives.
- Behaviour order and endpoint-filter order come from one shared list.