Module 1 · Hosting and the Request Pipeline · Lesson 2 of 18
The Request Pipeline: Middleware Order, Short-Circuits and Branches
The ASP.NET Core middleware pipeline enters components in order. Short-circuits skip later work, while branches send a request down a different path.
On a normal return, components that have already entered resume in reverse order. An escaping exception follows different rules: ordinary code after the downstream call is skipped.
This lesson follows how an ASP.NET Core app starts. Here, we focus on what happens after the app receives a request.
How does the ASP.NET Core middleware pipeline run?
Middleware is a component in the request pipeline that receives HttpContext and can call the next delegate or stop processing. The official middleware overview explains how components pass requests along and work before and after the next component. HttpContext holds the current request, response, user, and other information for that request.
In the console example below, A's next delegate enters B, which then calls the handler.
Earlier middleware therefore wraps later middleware:
flowchart TD
A["Middleware A"] -->|"calls next"| B["Middleware B"]
B -->|"calls next"| H["Request handler"]
H -->|"returns normally"| B
B -->|"returns normally"| A
The arrows show entry in registration order and normal return in reverse order.
ASP.NET Core builds this arrangement backwards. It starts with the delegate at the end, wraps that with the last registered component, and continues towards the first.
This console program demonstrates that composition using only C# delegates. It models the calling order, not HTTP processing. Compare its printed sequence with the diagram.
var trace = new List<string>();
var components = new List<Func<Func<Task>, Func<Task>>>
{
next => async () =>
{
trace.Add("A in");
await next();
trace.Add("A out");
},
next => async () =>
{
trace.Add("B in");
await next();
trace.Add("B out");
}
};
Func<Task> pipeline = () =>
{
trace.Add("handler");
return Task.CompletedTask;
};
for (int i = components.Count - 1; i >= 0; i--)
{
pipeline = components[i](pipeline);
}
await pipeline();
Console.WriteLine(string.Join(" -> ", trace));A in -> B in -> handler -> B out -> A out
The loop first wraps the handler with B. It then wraps that whole delegate with A. Calling the result enters A, then B, then the handler. Each await resumes when its downstream call completes normally.
The Build() method in the real ApplicationBuilder implementation uses this backwards composition.
The mistake to avoid. Registration does not execute middleware for a request. It builds the arrangement of delegates that requests will later enter.
In an interview, say: “Middleware receives HttpContext and can call the next delegate or stop processing. Earlier middleware wraps later middleware. Requests enter in registration order, and normal returns resume in reverse order.”
What is the difference between Use, Run and short-circuiting?
Use adds middleware that receives next. It can continue by calling next, or short-circuit by returning without calling it.
Run(handler) adds terminal middleware: a handler with no next parameter. Once reached, it does not continue to later components. This is different from parameterless app.Run(), which starts the host.
Short-circuiting skips downstream middleware. It does not skip the normal return through upstream middleware that has already entered. It also does not automatically write a response or set an error status.
The following example uses the real pipeline builder without starting a server. DefaultHttpContext supplies a request context for each check. It requires ASP.NET Core, so use an ASP.NET Core project rather than the console-only runner.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using var services = new ServiceCollection().BuildServiceProvider();
var app = new ApplicationBuilder(services);
var trace = new List<string>();
app.Use(async (context, next) =>
{
trace.Add("A in");
await next(context);
trace.Add("A out");
});
app.Use(async (context, next) =>
{
if (context.Request.Path == "/early")
{
trace.Add("early return");
return;
}
await next(context);
});
app.Use(async (context, next) =>
{
trace.Add("B in");
await next(context);
trace.Add("B out");
});
app.Run(context =>
{
trace.Add("terminal handler");
return Task.CompletedTask;
});
var pipeline = app.Build();
foreach (var path in new[] { "/normal", "/early" })
{
trace.Clear();
var context = new DefaultHttpContext();
context.Request.Path = path;
await pipeline(context);
Console.WriteLine($"{path}: {string.Join(" -> ", trace)}");
Console.WriteLine($"Status: {context.Response.StatusCode}");
}
var unhandled = new DefaultHttpContext();
await new ApplicationBuilder(services).Build()(unhandled);
Console.WriteLine($"Unhandled status: {unhandled.Response.StatusCode}");Needs ASP.NET Core (a web project). Built with it; not run here.
The program prints these traces and status lines:
/normal: A in -> B in -> terminal handler -> B out -> A outStatus: 200/early: A in -> early return -> A outStatus: 200Unhandled status: 404
For /early, the second component returns immediately. B and the terminal handler never run, but A still resumes.
Both paths leave status 200 in this example, although neither writes a body. The early return is not itself an error response.
The final check uses an empty pipeline. When you call Build(), ApplicationBuilder puts its own final delegate at the end of the pipeline. For a request that reaches it with no selected endpoint, this delegate sets status 404 unless the response has already started. If an endpoint was selected but never executed, it throws instead. This is the builder's fallback. That is different from reaching our terminal handler, which handles the request by completing normally. The fallback is defined in ApplicationBuilder.Build().
Use Use when work needs to surround or conditionally continue the pipeline. Choose Run(handler) when reaching that component should end downstream processing. See the official middleware guide for both forms.
The mistake to avoid. “Stops the pipeline” does not mean “nothing else runs.” A normal short-circuit still returns through middleware that already called next.
In an interview, say: “Use receives next and can continue or short-circuit. Run with a handler is terminal and has no next. Parameterless Run starts the host. A short-circuit skips downstream work, but normal upstream returns still happen, and it does not automatically create an error response.”
Does code after await next always run?
No. Code after await next(...) runs only when the downstream call completes normally. That includes a normal short-circuit.
If an exception propagates through the await, execution skips ordinary statements after it. Put required cleanup in finally, using the same rules as other asynchronous C# code.
This standalone console example isolates that difference:
static async Task Wrap(Func<Task> next)
{
Console.WriteLine("before next");
try
{
await next();
Console.WriteLine("after next");
}
finally
{
Console.WriteLine("cleanup");
}
}
foreach (bool fail in new[] { false, true })
{
Console.WriteLine(fail ? "Exception path:" : "Normal path:");
try
{
await Wrap(() => fail
? Task.FromException(new InvalidOperationException("Failure"))
: Task.CompletedTask);
}
catch (InvalidOperationException)
{
Console.WriteLine("caught outside wrapper");
}
}Normal path: before next after next cleanup Exception path: before next cleanup caught outside wrapper
On the normal path, both after next and cleanup print. On the exception path, only cleanup runs before the outer catch handles the exception.
Where an exception is caught matters. If downstream middleware catches it and returns normally, the caller's await next(...) completes normally too. If it escapes through that call, the caller skips its ordinary after-next code.
Exception-handling middleware therefore belongs early enough to surround the components whose exceptions it must handle. The C# exception-handling reference explains the underlying try and finally rules.
The mistake to avoid. Do not put resource cleanup only after await next(...). A downstream exception can bypass that line.
In an interview, say: “After-next code runs on normal downstream completion, including a normal short-circuit. An exception propagating through the await skips it. I use try/finally for cleanup that must run on both normal completion and exception propagation.”
What is the difference between Map, MapWhen and UseWhen?
A branch is a separate middleware pipeline chosen for some requests. Branching lets you give those requests different processing without adding conditions to every later component.
Request.Path holds the current request path. Request.PathBase holds a base prefix separated from that path.
| Method | How it matches | Path behaviour inside the branch | Does a matching branch rejoin later main middleware? |
|---|---|---|---|
Map | A path-segment prefix | Moves the matched prefix from Path into PathBase | No |
MapWhen | A predicate you supply | Does not rewrite the path | No |
UseWhen | A predicate you supply | Does not rewrite the path | Yes, if the branch continues |
A predicate here is simply a function that examines the context and returns true or false. A path-segment match means /branch matches /branch/item, but not /branching.
This ASP.NET Core example compares all three:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using var services = new ServiceCollection().BuildServiceProvider();
var app = new ApplicationBuilder(services);
var trace = new List<string>();
app.Use(async (context, next) =>
{
trace.Add("A in");
await next(context);
trace.Add("A out");
});
app.Map("/branch", branch =>
{
branch.Run(context =>
{
trace.Add($"Map: PathBase={context.Request.PathBase}; Path={context.Request.Path}");
return Task.CompletedTask;
});
});
app.MapWhen(context => context.Request.Path == "/probe", branch =>
{
branch.Run(context =>
{
trace.Add($"MapWhen: Path={context.Request.Path}");
return Task.CompletedTask;
});
});
app.UseWhen(context => context.Request.Path == "/audit", branch =>
{
branch.Use(async (context, next) =>
{
trace.Add("audit in");
await next(context);
trace.Add("audit out");
});
});
app.Run(context =>
{
trace.Add("main handler");
return Task.CompletedTask;
});
var pipeline = app.Build();
foreach (var path in new[] { "/plain", "/branch/item", "/probe", "/audit" })
{
trace.Clear();
var context = new DefaultHttpContext();
context.Request.Path = path;
await pipeline(context);
Console.WriteLine($"{path}: {string.Join(" -> ", trace)}");
}Needs ASP.NET Core (a web project). Built with it; not run here.
For /branch/item, the branch sees PathBase=/branch and Path=/item. It skips the main handler, then returns normally to A. The original path values are restored when the Map branch finishes, as shown by the cleanup in MapMiddleware.cs.
For /probe, MapWhen preserves /probe and also skips the main handler. For /audit, the branch calls next, reaches the main handler, then returns through the audit component and A.
The program prints these four traces:
/plain: A in -> main handler -> A out/branch/item: A in -> Map: PathBase=/branch; Path=/item -> A out/probe: A in -> MapWhen: Path=/probe -> A out/audit: A in -> audit in -> main handler -> audit out -> A out
Choose Map when the path prefix defines a separate area. Choose MapWhen for a separate pipeline selected by another condition. Choose UseWhen for conditional work that should normally continue through the main pipeline.
The important qualification is “if the branch continues.” A terminal handler inside UseWhen prevents rejoining. The UseWhen source shows how the main continuation is attached to the branch.
The mistake to avoid. Map and MapWhen do not fall through to later main middleware when their branch finishes. See MapMiddleware.cs and MapWhenMiddleware.cs. UseWhen goes back to the main pipeline only if every component reached in its branch calls next. If a component ends the request, for example with Run or by not calling next, the rest of the main pipeline does not run.
In an interview, say: “Map branches by path segment and moves the prefix into PathBase. MapWhen branches by a predicate without rewriting the path. Both skip later main middleware on a match. UseWhen rejoins the main pipeline if its branch continues.”
Why does middleware order matter for routing and security?
An endpoint is a request handler together with its routing information and associated settings. Endpoint routing matches a request to an endpoint. Later, endpoint middleware executes that selected endpoint.
The associated settings are called metadata. They can describe requirements such as who may access an endpoint.
Several middleware components depend on earlier work:
- CORS (cross-origin resource sharing) tells browsers which other websites may access this API's responses from their pages. An origin is the combination of scheme, host and port, such as
https://example.comwith its default HTTPS port. Endpoint-aware CORS needs routing to select the endpoint first. - Authentication establishes the current user's identity.
- Authorization checks whether that user may access the requested resource.
This complete web program makes the order explicit. It demonstrates placement, not a complete login setup.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy => policy
.WithOrigins("https://example.com")
.AllowAnyHeader()
.AllowAnyMethod());
});
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseExceptionHandler(errors => errors.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsync("Request failed.");
}));
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/hello", () => "Hello");
app.Run();Needs ASP.NET Core (a web project). Built with it; not run here.
Exception handling comes early so it surrounds later components. Static file middleware can serve a matching public file immediately. Files served there bypass the later CORS, authentication, and authorization components. This placement is suitable for public files, not a way to protect private files.
After routing, the order is CORS, authentication, then authorization. This allows each component to use the information it needs. There is no configured login mechanism or authorization requirement on /hello in this sample.
Notice that MapGet registers an endpoint. It does not insert its handler at that line in the middleware chain. Routing selects the endpoint; endpoint middleware executes it later.
WebApplication can add routing and endpoint execution automatically when endpoints are configured. It can also add authentication and authorization middleware when the corresponding services are registered. In Development, it adds the Developer Exception Page first; this middleware shows details of unhandled exceptions. With endpoints configured, automatic routing goes near the start, after that exception page, unless you call UseRouting yourself. Automatic endpoint execution goes at the end. The official Middleware in Minimal API apps page describes these rules. Explicit calls let you choose placement relative to your own middleware. Do not assume every executing component appears as a Use line in your file.
Continue with endpoint routing internals for how selection works, or the authentication and authorization pipeline for access checks.
The mistake to avoid. Do not treat endpoint registration order as middleware execution order, or expect later authorization to protect a response already served by static file middleware.
In an interview, say: “Earlier middleware wraps later middleware. Put exception handling early, routing before endpoint-aware CORS and authorization, CORS before authentication and authorization, and authentication before authorization. Early public static files bypass later checks. MapGet registers an endpoint, not an execution slot, and WebApplication can add middleware automatically.”
Can you change response headers after calling next?
Only if the response has not started. HasStarted is true once the server has begun sending the response. At that point, the status code and headers have been sent to the client and can no longer be changed. This is what “committed” means here. Ordinary changes to headers or the status code then throw exceptions.
Returning from next does not prove that the response has started. Downstream code might only have selected a status code without sending anything. Equally, downstream code might have started the response long before returning.
OnStarting registers a callback that runs just before headers are sent. Register it before calling next so that it is already in place if downstream code starts the response.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers["X-Pipeline"] = "example";
return Task.CompletedTask;
});
await next(context);
if (!context.Response.HasStarted)
{
context.Response.Headers["X-Returned-Before-Start"] = "true";
}
});
app.MapGet("/headers-only", (HttpContext context) =>
{
context.Response.StatusCode = StatusCodes.Status204NoContent;
});
app.MapGet("/body", async (HttpContext context) =>
{
await context.Response.WriteAsync("Hello");
});
app.Run();Needs ASP.NET Core (a web project). Built with it; not run here.
The callback adds X-Pipeline at header commitment, including when the body-writing handler starts the response. The after-next code adds its other header only when HasStarted is still false. It makes no assumption based solely on next having returned.
Do not casually append body text after next either. A downstream response may have a fixed content length or a format that your extra text would corrupt.
See request and response operations, including StartAsync, which makes headers unmodifiable and runs OnStarting callbacks.
The mistake to avoid. When next returns, you do not know whether the response has started. Check HasStarted before you change headers.
In an interview, say: “I can change headers after next only if the response has not started. HasStarted tells me whether headers are committed. For a header that should be set just before commitment, I register OnStarting before calling next.”
How do you write custom middleware?
The examples use inline delegates so the order is visible. Convention-based middleware moves that work into a class. Its constructor receives RequestDelegate, the delegate type representing the next pipeline. Its Invoke or InvokeAsync method receives HttpContext. Register the class with UseMiddleware<T>(), where T is your middleware class.
Such middleware is constructed at application startup, not once per request. A scoped service is a dependency whose instance is shared within a scope, usually one request. Request-scoped dependencies belong in InvokeAsync parameters rather than the middleware constructor. The official custom middleware guide shows that pattern.
Factory-based middleware implements IMiddleware and is registered through dependency injection (DI), which supplies the registered objects a class needs. It is activated per request using its registered lifetime. Registering it as scoped or transient allows it to receive scoped services in its constructor. See factory-based middleware activation.
The mistake to avoid. Do not assume every middleware class has the same lifetime. A convention-based instance is shared across requests, so request-scoped constructor dependencies do not belong there.
In an interview, say: “For convention-based middleware, I take RequestDelegate in the constructor, write Invoke or InvokeAsync, and register it with UseMiddleware. The instance lives for the app, so scoped services go in InvokeAsync parameters. IMiddleware is the factory-based alternative, activated per request using its registered lifetime.”
Check yourself
A middleware logs "before", awaits next, then logs "after". Downstream middleware returns normally without calling its own next. What happens?
Show answer
Correct answer: D
The downstream short-circuit completes normally, so the awaiting middleware resumes. Skipping next does not itself set a response status.
A matching UseWhen branch contains middleware that calls next, and no component in that branch terminates processing. Where does execution continue?
Show answer
Correct answer: A
UseWhen attaches the main continuation to its branch. Unlike Map, it does not rewrite the request path.
Going deeper
An empty branch is not necessarily a pass-through
A matched Map or MapWhen branch has its own pipeline ending. If nothing handles the request there, an ordinary unhandled request receives 404 rather than falling through to the main pipeline. With UseWhen, a branch that continues reaches the main continuation instead.
Exception handling cannot rewind a committed response
Early exception handling gives it the opportunity to catch downstream failures. It does not make an already-started response replaceable. Once headers are committed, changing the result into a fresh error response is no longer generally possible. Continue with exception handling and ProblemDetails for that boundary.
A finally block provides cleanup during normal completion and exception propagation. It is not a guarantee against process termination, and cleanup code can itself throw.
Sources
- MapMiddleware.cs · dotnet/aspnetcore: Matching branches, path-prefix movement, and restoration of Path and PathBase.
- MapWhenMiddleware.cs · dotnet/aspnetcore: Matching requests execute the branch rather than the later main pipeline.
- Middleware in Minimal API apps | Microsoft Learn: Automatically added exception handling, routing, authentication, authorization, and endpoint execution.
- Factory-based middleware activation in ASP.NET Core | Microsoft Learn: IMiddleware activation, registered lifetimes, and scoped constructor dependencies.
- ASP.NET Core middleware | Microsoft Learn: Middleware execution, Use and terminal Run, short-circuiting, branches, middleware ordering, public static files, and response-start restrictions.
- Write custom ASP.NET Core middleware | Microsoft Learn: HttpContext, convention-based middleware, RequestDelegate, application-lifetime construction, and request-scoped InvokeAsync dependencies.
- aspnetcore/src/Http/Http/src/Builder/ApplicationBuilder.cs at release/10.0 · dotnet/aspnetcore · GitHub: Reverse composition of registered components and the ordinary unhandled-request 404 fallback.
- aspnetcore/src/Http/Http.Abstractions/src/Extensions/UseWhenExtensions.cs at release/10.0 · dotnet/aspnetcore · GitHub: UseWhen attaches the main continuation to the branch, allowing rejoining only if branch execution continues.
- Request and Response operations in ASP.NET Core | Microsoft Learn: StartAsync commits headers and runs OnStarting callbacks.
- Exception-handling statements - throw and try, catch, finally - C# reference | Microsoft Learn: Normal completion versus exception propagation, finally cleanup, and process-termination limitations.
- aspnetcore/src/DefaultBuilder/src/WebApplicationBuilder.cs at release/10.0 · dotnet/aspnetcore · GitHub: WebApplication's automatic routing, authentication, authorization, and endpoint middleware, and explicit ordering.
- aspnetcore/src/DefaultBuilder/src/WebApplication.cs at release/10.0 · dotnet/aspnetcore · GitHub: Distinguishing WebApplication.Run(), which runs the host, from terminal Run(RequestDelegate).
Practice
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 28 Nov 2026 ·