Chain of Responsibility intent and structure, the classic handle-or-pass chain (approval limits) vs the pipeline variant where every handler can act before and after next, ASP.NET Core middleware (RequestDelegate next), DelegatingHandler, short-circuiting, the recommended middleware order, and the costs of long implicit chains.
Chain of Responsibility sends a request along a chain of handlers; each one decides whether to handle it, pass it on, or both, and the sender doesn't know which one acted.
next. ASP.NET Core middleware (RequestDelegate next) and DelegatingHandler in HttpClient work this way.Short-circuiting means returning without calling next: authentication returning 401, static files serving a file, a cache hit. That's why order matters: exception handling must wrap everything, and authentication must run before authorisation.
The trade-off is decoupling and composability against long implicit chains whose order lives far from the handlers.
"Chain of Responsibility is about decoupling the sender of a request from whoever ends up handling it. You line up handlers, give the request to the first one, and each handler either deals with it or passes it to the next. The textbook example is an expense approval: a team lead can approve up to $1,000, a manager up to $10,000, a director above that. The request walks the chain until someone with enough authority takes it, and the person submitting it doesn't need to know who that is.
In .NET you mostly meet the pipeline variant, where every handler gets a chance to act before and after the next one. ASP.NET Core middleware is exactly that: each middleware receives the
HttpContextand aRequestDelegate next, does some work, callsawait next(context), and can do more work as the response comes back. Outgoing HTTP is the mirror image: eachDelegatingHandleroverridesSendAsync, does something, and callsbase.SendAsyncto reach the inner handler, ending atSocketsHttpHandler. Short-circuiting is just not callingnext: the static files middleware serves the file and stops; the authorisation middleware returns 401 or 403; a response cache returns the cached body. Everything after that never runs.Which is why order matters so much. If exception handling isn't first, exceptions in earlier middleware escape it. If authorisation runs before authentication, there's no user to authorise. If static files sit after authentication, every image request pays for auth. The mistake I see is adding middleware in whatever order it was written and only finding out in production that, say, the rate limiter runs after an expensive step it was meant to protect. In a chain, the order is part of the design; I read
Program.cstop to bottom as the request's path."
| Classic Chain of Responsibility | Pipeline (middleware, handlers) | |
|---|---|---|
| Who acts | The first handler that can handle it | Potentially every handler |
| Before/after | Only one action point | Code before and after next |
| Typical example | Approval limits, support escalation, event routing | ASP.NET Core middleware, DelegatingHandler, MediatR behaviours |
| Unhandled request | Falls off the end: needs a default | Reaches the terminal handler (endpoint, SocketsHttpHandler) |
| Position | Middleware | Why there |
|---|---|---|
| 1 | UseExceptionHandler / UseDeveloperExceptionPage |
Must wrap everything to catch exceptions |
| 2 | UseHsts, UseHttpsRedirection |
Redirect before doing work |
| 3 | UseStaticFiles |
Short-circuits file requests cheaply |
| 4 | UseRouting |
Selects the endpoint (added implicitly by WebApplication if omitted) |
| 5 | UseCors |
Needs the endpoint, before auth for preflight |
| 6 | UseAuthentication, UseAuthorization |
Identify, then authorise |
| 7 | UseRateLimiter, UseOutputCache |
Need the endpoint and user |
| 8 | Endpoints (MapControllers, MapGet) |
Terminal handlers |
An API placed a custom request-logging middleware that read the whole request body before UseRateLimiter. During a scraping burst, every rejected request still paid for body buffering, and memory hit about 1.8 GB. Moving the rate limiter ahead of the logging middleware (and only logging bodies for accepted requests) cut memory under the same load to about 400 MB and rejected requests in under 1 ms.
Checks that the candidate recognises Chain of Responsibility in middleware and HTTP handlers, understands short-circuiting and knows why order matters.
Green flags
next and short-circuiting with concrete middleware.Red flags
Client βββΆ Handler1 ββnextβββΆ Handler2 ββnextβββΆ Handler3 βββΆ (default / terminal)
β β β
handle or pass handle or pass handle or pass
Β«abstractΒ» Handler
next: Handler?
Handle(request) { if (CanHandle) ... else next?.Handle(request) }
The sender only knows the head of the chain. Handlers know only the abstraction of the next handler, so the chain can be rearranged or extended without touching the sender.
app.Use(...) adds a Func<RequestDelegate, RequestDelegate> to a list. When the app starts, ApplicationBuilder.Build() walks that list in reverse, wrapping the terminal delegate (which returns 404 if nothing matched) with each middleware, so the first registered middleware ends up outermost:
Request ββΆ ExceptionHandler ββΆ StaticFiles ββΆ Routing ββΆ Auth ββΆ Endpoint
Response ββ ExceptionHandler ββ StaticFiles ββ Routing ββ Auth βββ
app.Use(async (ctx, next) => { ...; await next(ctx); ... }): pre and post.app.Run(...): terminal; never calls next.app.Map("/path", branch) / MapWhen: branches the chain.RequestDelegate next in the constructor and expose InvokeAsync(HttpContext); IMiddleware implementations are resolved from DI per request.DelegatingHandler chainsEach DelegatingHandler has an InnerHandler. IHttpClientFactory builds the chain from AddHttpMessageHandler<T>() calls, with the first call outermost and the primary handler (SocketsHttpHandler) innermost. A handler can short-circuit by returning an HttpResponseMessage without calling base.SendAsync, which is how fake handlers in tests and cache handlers work.
Once a middleware starts writing the response, headers are sent and later middleware can't change status codes or headers (HttpResponse.HasStarted). A middleware that short-circuits should set the status and write the body itself. Middleware after a short-circuit sees nothing, so logging or metrics middleware must sit outside anything that might short-circuit if it needs to see every request.
Useful when rules are ordered and the first match wins: approval limits, discount eligibility, routing a support ticket, choosing a parser by file signature. In DI, register handlers in order and build the chain from IEnumerable<IHandler> (registration order is preserved), or iterate the list and stop at the first handler that returns a result. Always define what happens when nobody handles the request.
Program.cs) and invisible from the handler classes; reviewers must read the whole registration.next silently swallows requests.app.Use middleware that log before and after next; confirm the nested order in the console./health and see which logs disappear.UseAuthorization above UseAuthentication and observe the 401s on an [Authorize] endpoint.IEnumerable<IApprovalHandler> and test an amount nobody can approve.DelegatingHandlers and verify their order with AddHttpMessageHandler.A pipeline-style middleware that short-circuits, the order in Program.cs, and a classic first-match chain.
namespace Api;
// Pipeline variant: acts before next, may short-circuit, can act after
public sealed class ApiKeyMiddleware(RequestDelegate next, IConfiguration config)
{
private readonly string? _expected = config["ApiKey"];
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("X-Api-Key", out var key) || key != _expected)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized; // short-circuit: next never runs
return;
}
await next(context); // pass it on
context.Response.Headers.Append("X-Handled-By", "api"); // only if headers not yet sent
}
}
// Program.cs: the order below IS the request path
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();
builder.Services.AddRateLimiter(o => o.AddFixedWindowLimiter("api", w => { w.PermitLimit = 100; w.Window = TimeSpan.FromMinutes(1); }));
var app = builder.Build();
app.UseExceptionHandler("/error"); // 1. wraps everything below
app.UseHttpsRedirection(); // 2.
app.UseStaticFiles(); // 3. short-circuits file requests before auth
app.UseRouting(); // 4.
app.UseAuthentication(); // 5. who are you
app.UseAuthorization(); // 6. are you allowed
app.UseRateLimiter(); // 7. after routing so endpoint policies apply
app.UseMiddleware<ApiKeyMiddleware>();
app.MapGet("/orders", () => Results.Ok()).RequireRateLimiting("api"); // terminal handler
app.Run();
namespace Expenses;
// Classic variant: the first handler that can handle it wins
public sealed record ExpenseClaim(string Employee, decimal Amount);
public interface IApprovalHandler
{
string? TryApprove(ExpenseClaim claim); // returns approver, or null to pass on
}
public sealed class TeamLeadApproval : IApprovalHandler
{
public string? TryApprove(ExpenseClaim c) => c.Amount <= 1_000m ? "Team lead" : null;
}
public sealed class ManagerApproval : IApprovalHandler
{
public string? TryApprove(ExpenseClaim c) => c.Amount <= 10_000m ? "Manager" : null;
}
public sealed class DirectorApproval : IApprovalHandler
{
public string? TryApprove(ExpenseClaim c) => c.Amount <= 100_000m ? "Director" : null;
}
// IEnumerable<T> preserves registration order, so the chain order is the DI order
public sealed class ApprovalChain(IEnumerable<IApprovalHandler> handlers)
{
public string Approve(ExpenseClaim claim) =>
handlers.Select(h => h.TryApprove(claim)).FirstOrDefault(a => a is not null)
?? throw new InvalidOperationException($"No approver for {claim.Amount:C}; escalate to the board.");
}
// builder.Services.AddSingleton<IApprovalHandler, TeamLeadApproval>();
// builder.Services.AddSingleton<IApprovalHandler, ManagerApproval>();
// builder.Services.AddSingleton<IApprovalHandler, DirectorApproval>();
// builder.Services.AddSingleton<ApprovalChain>();
UseExceptionHandler after other middleware. Why it is wrong: Exceptions thrown before it in the chain escape it and return raw 500s. Instead: Register exception handling first.UseAuthorization before UseAuthentication. Why it is wrong: No user has been established, so [Authorize] endpoints reject everyone. Instead: Authentication, then authorisation, both after routing.await next(context) without checking Response.HasStarted. Why it is wrong: Headers have already been sent, so it throws or is ignored. Instead: Use Response.OnStarting or set headers before calling next.next on some code path. Why it is wrong: Requests silently stop with an empty 200. Instead: Make every path either call next or write a full response; test both.if/else would do. Why it is wrong: Extra types for three fixed rules that never change. Instead: Use a chain when handlers are added, reordered or configured independently.Most of the value of Chain of Responsibility in .NET comes from using the framework's chains correctly rather than building your own. My review checklist for any pipeline is: what can short-circuit, what must see every request (so sits outside those), and what is expensive (so sits after the cheap rejections).
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| ASP.NET Core middleware | Concerns for every HTTP request | Order is global and implicit | Per-endpoint concerns (use endpoint filters) |
| Endpoint filters / MVC filters | Concerns for specific endpoints | Only within routing | App-wide concerns |
DelegatingHandler |
Outgoing HTTP concerns | Per named/typed client | Non-HTTP dependencies |
| Custom classic chain | Ordered first-match business rules | One class per rule | Two or three fixed rules |
Ordered if/else |
Small, stable rule set | Edits one method | Rules added or reordered by others |
When diagnosing order problems, I log middleware entry and exit in a test environment or use Microsoft.AspNetCore debug logging, and I keep a test that hits a protected endpoint without credentials to catch auth-order regressions.
All three symptoms come from wrapper order and duplication. The outermost decorator or handler runs first and can short-circuit everything inside it.
AddStandardResilienceHandler. The standard pipeline is already rate limiter β total timeout β retry β circuit breaker β attempt timeout.To diagnose, list the ServiceDescriptors, walk the resolved chain, inspect the handler order, and read span nesting in traces. Then compose the chain in one place and add tests that assert its order and attempt counts.
Decorator wraps an object in another object that implements the same interface, adds behaviour before or after delegating, and is invisible to callers. Decorators stack: logging around caching around the real repository. Each concern is one small class, so the original stays untouched (Open/Closed).
.NET uses it everywhere: GZipStream(BufferedStream(FileStream)), CryptoStream, and DelegatingHandler pipelines in HttpClient.
The built-in container has no Decorate method. You register the inner type concretely and the interface with a factory delegate, use a keyed inner service, or use Scrutor's Decorate<TService, TDecorator>().
The trade-off is that order matters and long chains are harder to debug.
The GoF Mediator stops objects talking to each other directly: colleagues send messages to a mediator, which turns many-to-many coupling into many-to-one (a dialog coordinating its controls).
MediatR is really an in-process request dispatcher: Send(IRequest<T>) goes to exactly one handler, Publish(INotification) to many, and IPipelineBehavior wraps every handler with validation, logging or transactions.
It's indirection for nothing when an endpoint just sends to a handler that calls a repository: injecting the handler gives the same decoupling, and "go to definition" still works.
Licensing: since v13 (July 2025) MediatR is dual RPL-1.5 / commercial under Lucky Penny Software, free (Community edition) under US$5M revenue; 12.5.0 is the last Apache 2.0 version.
Alternatives: direct handler injection with decorators, or a source-generated mediator. The trade-off is uniform pipelines vs traceable, explicit code.
Last updated 18 Nov 2026.