5.7 — Short-Circuiting and Terminal Middleware¶
← Roadmap · Section: 5. Middleware and the Request Pipeline Prev: 5.6 IMiddleware factory · Next: 5.8 HttpContext
Markers: ⭐ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Short-circuiting means a middleware decides not to call next, so the request stops there
and that middleware produces the response itself.
- It is done simply by not calling
next()— usually with an earlyreturn. - Everything registered below is skipped. Everything above still gets its "after" half.
- This is how static files, authorization failures, rate limiting and caching all work.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Short-circuit | a behaviour | Not calling next, so the rest of the pipeline is skipped. |
| Terminal middleware | a role | Middleware that never calls next at all — the end of the line. |
app.Run(handler) |
an extension method | Adds terminal middleware. Its signature has no next. |
| Unwinding | what happens next | Control returns up through the middleware that already called next. |
return |
a C# statement | How you short-circuit. Simply stop before reaching next. |
| Empty 200 | a failure symptom | What the caller gets when you short-circuit without writing a response. |
context.Response.StatusCode |
a property | Set this before writing, or the default 200 is sent. |
Results / TypedResults |
static classes | Helpers for producing responses in minimal APIs and endpoint filters. |
ShortCircuit() |
an endpoint method (.NET 8+) | Marks an endpoint to skip most of the pipeline for performance. |
The concept¶
It is just an early return¶
There is no special API for short-circuiting. You simply do not call next:
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/blocked"))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
await context.Response.WriteAsync("Not allowed");
return; // ← the short circuit. No next().
}
await next(); // the normal path
});
That is the entire mechanism.
A picture: a security desk in a corridor of desks. Normally they check you and wave you through to the next desk. When something is wrong they hand you a rejection slip and turn you around — you never see the desks further down.
What still runs¶
This is the part worth being precise about. Short-circuiting skips everything downstream,
but middleware upstream has already called next and is waiting — so their "after" code
still runs as the call unwinds.
app.Use(async (context, next) =>
{
Console.WriteLine("A: before");
await next();
Console.WriteLine("A: after"); // ← STILL RUNS
});
app.Use(async (context, next) =>
{
Console.WriteLine("B: short-circuiting");
context.Response.StatusCode = 403;
return; // no next()
});
app.Run(async context =>
{
Console.WriteLine("C: never reached");
});
Output:
That is essential, and it is why logging, timing and exception-handling middleware keep working even when a request is rejected early. They are wrapped around the short-circuit, not bypassed by it.
How it works¶
The simple version — where it already happens¶
Most short-circuiting in your app is done by middleware you did not write:
| Middleware | Short-circuits when |
|---|---|
UseStaticFiles |
The path matches a file in wwwroot — serves it and stops |
UseAuthorization |
The user fails the policy — returns 401 or 403 |
UseRateLimiter |
The limit is exceeded — returns 429 |
UseCors |
A preflight OPTIONS request — answers it directly |
UseResponseCaching |
A cached response exists — returns it without hitting the endpoint |
UseHttpsRedirection |
The request is HTTP — returns a 307 redirect |
Static files is the one to understand, because it explains the ordering rule from
5.2. A request for /logo.png matches a file, so that middleware
writes it and returns. Authentication, authorization and routing below it never execute — which
is why placing static files early saves real work, and why files in wwwroot are not protected
by [Authorize] (4.10).
⚠️ The empty 200 trap¶
The most common bug here:
app.Use(async (context, next) =>
{
if (!IsValid(context))
{
return; // ✗ short-circuits, but writes NOTHING
}
await next();
});
The caller gets HTTP 200 with an empty body. No error, no status code, nothing to debug
from — because StatusCode defaults to 200 and you never changed it.
Always set a status code and ideally write a body:
if (!IsValid(context))
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
context.Response.ContentType = "application/problem+json";
await context.Response.WriteAsJsonAsync(new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Invalid request"
});
return;
}
Using ProblemDetails keeps your error shape consistent with the rest of the API —
10.8.
Terminal middleware — app.Run¶
Run is short-circuiting made structural. Its delegate has no next parameter, so
continuing is impossible:
app.Run(async context =>
{
await context.Response.WriteAsync("This always ends here");
});
app.UseAuthentication(); // ⚠️ unreachable — nothing after Run ever executes
Registering middleware after Run compiles fine and silently never runs. Covered in
5.3.
Your endpoints are effectively terminal middleware — MapControllers sits at the end of the
pipeline and produces the response.
The deeper detail — the .NET 8 ShortCircuit() optimisation¶
.NET 8 added a way to skip most of the pipeline for specific endpoints:
app.MapGet("/healthz", () => Results.Ok()).ShortCircuit();
// Or with a status code, skipping even the handler
app.MapGet("/robots.txt", () => "User-agent: *").ShortCircuit(200);
Normally routing happens early and the endpoint runs at the end, so a health check still passes
through authentication, authorization, CORS and everything else. ShortCircuit() tells the
routing middleware to execute the endpoint immediately after matching, skipping the
middleware in between.
Use it for high-volume endpoints that need no pipeline — health checks polled every few
seconds, robots.txt, favicon.ico.
⚠️ Be careful. It skips authentication and authorization too. Applying it to anything sensitive removes your security middleware from that path entirely. Health endpoints are the intended case precisely because they are meant to be unauthenticated.
Code¶
A realistic short-circuiting middleware — an API key check:
internal class ApiKeyMiddleware(RequestDelegate next, ILogger<ApiKeyMiddleware> logger)
{
private const string HeaderName = "X-Api-Key";
public async Task InvokeAsync(HttpContext context, IApiKeyValidator validator)
{
// Only guard /api — everything else passes straight through
if (!context.Request.Path.StartsWithSegments("/api"))
{
await next(context);
return;
}
if (!context.Request.Headers.TryGetValue(HeaderName, out var provided))
{
await WriteProblemAsync(context, StatusCodes.Status401Unauthorized,
"Missing API key");
return; // short-circuit
}
if (!await validator.IsValidAsync(provided!, context.RequestAborted))
{
logger.LogWarning("Rejected invalid API key from {Ip}",
context.Connection.RemoteIpAddress);
await WriteProblemAsync(context, StatusCodes.Status403Forbidden,
"Invalid API key");
return; // short-circuit
}
await next(context); // valid — carry on
}
private static async Task WriteProblemAsync(HttpContext context, int status, string title)
{
context.Response.StatusCode = status;
context.Response.ContentType = "application/problem+json";
await context.Response.WriteAsJsonAsync(new ProblemDetails
{
Status = status,
Title = title
});
}
}
Three things worth noticing:
- Every short-circuit path sets a status code and writes a body. No silent empty 200s.
- The non-matching path calls
nextand returns, so unrelated requests are unaffected. context.RequestAbortedis passed down, so a disconnected client stops the validation work (2.14).
Checking whether the response already started¶
Before short-circuiting after calling next, check that nothing has been written:
await next(context);
if (!context.Response.HasStarted)
{
context.Response.Headers["X-Handled-By"] = "MyMiddleware";
}
Once the response has started, headers and status code are already on the wire and any modification throws. See 5.8.
Interview questions¶
Q: What does it mean to short-circuit the pipeline?
It means a middleware decides not to call the next delegate, so the request stops there and that
middleware produces the response itself. There is no special API — you simply return before
reaching next. Everything registered below is skipped, but middleware above has already called
next and is awaiting it, so their code after that await still runs as the call unwinds. That
is important, because it means logging, timing and exception handling continue to work for
requests that are rejected early.
Q: Where does short-circuiting already happen in a typical app?
In most of the built-in middleware. Static files short-circuits when the path matches a file in
wwwroot, serving it without running anything below — which is why placing it early saves work
and why files there are not protected by authorization. Authorization short-circuits with 401 or
403 when a policy fails. Rate limiting returns 429, response caching returns a cached body
without touching the endpoint, and CORS answers preflight requests directly.
Q: What is the most common bug when writing short-circuiting middleware?
Returning without writing anything. The caller then gets an HTTP 200 with an empty body, because
the status code defaults to 200 and you never set it — so there is nothing to diagnose from.
Every short-circuit path should set an explicit status code and ideally write a body, and using
ProblemDetails keeps the error shape consistent with the rest of the API.
Q: What is ShortCircuit() in .NET 8?
An endpoint-level optimisation. Normally routing matches early but the endpoint executes at the
end of the pipeline, so even a health check passes through authentication, authorization and
everything else. Calling .ShortCircuit() on an endpoint tells the routing middleware to run it
immediately after matching, skipping the middleware in between. It suits high-volume endpoints
that need no pipeline — health checks, robots.txt. The caveat is that it skips authentication
and authorization too, so it must never be applied to anything sensitive.
Traps ⚠️¶
- Returning without writing a response gives an empty 200. Always set a status code.
- Middleware after
app.Run(handler)never executes. It compiles and silently does nothing. - Short-circuiting does not skip upstream "after" code. Those middleware still unwind.
- Modifying the response after it has started throws. Check
HasStartedfirst. ShortCircuit()skips authentication and authorization. Only for genuinely public endpoints.- Short-circuiting before
UseExceptionHandlermeans your error is not formatted by it. - Forgetting
returnafter writing a response lets execution continue tonext, producing a second response and an exception.
Related¶
- 5.1 What middleware is — the nesting that makes unwinding work
- 5.2 Middleware order — why early short-circuits save work
- 5.3 Use, Run, Map — terminal middleware
- 5.8 HttpContext —
HasStartedand writing responses - 4.10 Static files — the classic short-circuit
- 10.8 ProblemDetails — consistent error bodies
- 17.10 Rate limiting — short-circuiting with 429