Advertisement
Intermediate .NET, ASP.NET Core Middleware & Request Pipeline

How does short-circuiting work in middleware, and when would you deliberately not call next()?

Short answer

A middleware short-circuits the pipeline by writing a response and simply not calling await next(), preventing any subsequent middleware or the endpoint from ever executing for that request.

Save .NET mock interview
Advertisement
AModel answer
A middleware short-circuits the pipeline by writing a response and simply not calling await next(), preventing any subsequent middleware or the endpoint from ever executing for that request. This is commonly used for early validation failures, rate limiting rejections, maintenance-mode responses, or cached responses -- any case where you can definitively answer the request without needing the rest of the pipeline.
app.Use(async (context, next) => {
    if (context.Request.Headers["X-Maintenance-Bypass"] != "true" && IsMaintenanceMode()) {
        context.Response.StatusCode = 503;
        await context.Response.WriteAsync("Service under maintenance");
        return;  // short-circuit: next() never called
    }
    await next();
});
Real-world example
A rate-limiting middleware short-circuits with a 429 Too Many Requests response the moment a client exceeds their quota, avoiding the cost of running authentication, routing, and the actual endpoint logic unnecessarily.
Likely follow-ups
  • What happens to response headers already set if you short-circuit late in the pipeline?
  • How does this interact with the exception handling middleware wrapping everything?
Related topics