skip to content

Middleware Order & Branching

Building the pipeline from RequestDelegate with Use, Run, Map and UseWhen, in the order the docs prescribe from exception handler to endpoints. Interviewers ask what breaks when one call moves.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core, what is a RequestDelegate, and how do app.Use and app.Run differ when you build the request pipeline?

level: juniorimportance: must knowfreq 78%

answer

  1. Task-returning delegate over HttpContext
  2. Use receives next, Run does not
  3. Run is terminal: later registrations never run
  4. returning without next short-circuits
  5. pipeline end: 404 if nothing answered

basics

~10 s

RequestDelegate is the Task-returning delegate that handles one HttpContext. app.Use adds middleware that receives the next delegate and may call it; app.Run adds terminal middleware with no next, so nothing registered after it runs.

solid answer

~40 s

`RequestDelegate` is `Task (HttpContext context)`: the whole pipeline, and each piece of it, has that shape. `app.Use((context, next) => ...)` adds middleware that gets the rest of the pipeline as `next`; it can work before and after `await next(context)`, or return without calling it to short-circuit. `app.Run(context => ...)` adds **terminal** middleware: it is a plain `RequestDelegate` with no `next`, so anything registered after it is never reached. Prefer the `Use` overload whose `next` takes the `HttpContext`, which saves two per-request allocations. If every middleware delegates and nothing answers, the pipeline's own end sets 404. Don't confuse `app.Run(handler)` with the parameterless `app.Run()` on `WebApplication`, which starts the host.

code

csharp · 21 lines
csharp
var app = builder.Build();

app.Use(async (context, next) =>
{
    context.Response.Headers["X-Guide-Version"] = "2";
    await next(context);            // hand over to the rest of the pipeline
});

app.Use(async (context, next) =>
{
    if (context.Request.Path == "/ping")
    {
        await context.Response.WriteAsync("pong");
        return;                     // short-circuit: next is never called
    }
    await next(context);
});

app.Run(context => context.Response.WriteAsync("Audio guide API")); // terminal middleware

app.Run();                          // WebApplication.Run: starts the host

go deeper

for a junior

Recall the RequestDelegate shape, that Use gets next and Run does not, and that returning without next short-circuits the rest.

for a middle

Explain how Build folds the registrations into nested delegates, why the context-passing Use overload is preferred, and what the built-in end of the pipeline does.

for a senior

Show you can read a Program.cs and predict which middleware runs for a request, including dead code after a terminal Run and the two Run methods on WebApplication.

for a principal

Discuss when inline lambdas should become named middleware classes so a growing pipeline stays reviewable and testable across teams.

## RequestDelegate: the unit of the pipeline In ASP.NET Core every request is handled by a **`RequestDelegate`**, a delegate with the signature `Task RequestDelegate(HttpContext context)`. The application builder (`IApplicationBuilder`, which `WebApplication` implements) collects a list of components, each of the shape `Func<RequestDelegate, RequestDelegate>`: given the *next* delegate, return a new delegate that wraps it. When the host starts, `ApplicationBuilder.Build()` folds that list from the last registration to the first, so the delegate it returns is the outermost middleware, holding a reference to the one registered after it, and so on down. The innermost delegate is one the framework supplies. It runs when every component delegated onward and none answered: - if the response has not started, it sets the status code to **404**; - if routing had selected an endpoint that never executed (endpoint routing without the endpoint middleware), it throws an `InvalidOperationException` saying the request reached the end of the pipeline without executing the endpoint. ## app.Use: middleware that can delegate `app.Use` registers middleware that is handed the rest of the pipeline. Two inline overloads exist: | Overload | What `next` is | Note | |---|---|---| | `Use(Func<HttpContext, RequestDelegate, Task>)` | a `RequestDelegate`; call `next(context)` | preferred: saves two per-request allocations | | `Use(Func<HttpContext, Func<Task>, Task>)` | a parameterless `Func<Task>`; call `next()` | older shape, wraps a closure per request | Inside the lambda you decide three things: what to do **before** `await next(context)`, whether to call it at all, and what to do **after** it returns. Returning without calling `next` **short-circuits**: later middleware and the endpoint never run, while middleware registered *earlier* still runs the code after its own `await next(context)`. ## app.Run: terminal middleware `app.Run(RequestDelegate handler)` is the `RunExtensions.Run` extension. Under the hood it is `app.Use(_ => handler)`: it ignores whatever `next` would have been, so it **always** ends the pipeline. Anything you register after it with `Use`, `Run` or `Map` is dead code for the requests that reach it. A common slip in a `WebApplication` Program.cs is to mix up two methods named `Run`: 1. `app.Run(async context => ...)`: adds terminal middleware (an extension on `IApplicationBuilder`). 2. `app.Run()`: `WebApplication.Run`, which starts the server and blocks until shutdown. It is the last line of the file and adds nothing to the pipeline. ## A worked pipeline For a museum audio-guide API, a timing middleware wraps everything, a health ping answers by itself, and a terminal fallback catches the rest: ```csharp app.Use(async (context, next) => { var started = DateTime.UtcNow; await next(context); app.Logger.LogInformation("{Path} {Status} in {Ms} ms", context.Request.Path, context.Response.StatusCode, (DateTime.UtcNow - started).TotalMilliseconds); }); app.Use(async (context, next) => { if (context.Request.Path == "/ping") { await context.Response.WriteAsync("pong"); return; // next is skipped } await next(context); }); app.Run(context => context.Response.WriteAsync("Audio guide API")); ``` A request for `/ping` enters the timing middleware, is answered by the second one, and unwinds back through the timing middleware, which still logs it. Every other request reaches the terminal `Run`. ## Reading the chain as nested calls Because `Build()` wraps each component around the next one, a request to `/tours/7` in that pipeline executes like nested method calls: 1. The timing middleware records the start time and awaits `next(context)`. 2. The ping middleware checks the path, finds no match, and awaits `next(context)`. 3. The terminal `Run` handler writes the body and returns; it has no `next` to call. 4. Control returns into the ping middleware after its `await`; it has nothing left to do. 5. Control returns into the timing middleware, which logs the elapsed time and the final status code. Two consequences follow. First, the code after `await next(context)` sees the response **as the inner components left it**, which is why a timing or logging middleware belongs on the outside. Second, an exception thrown by an inner component propagates outward through the same awaits, so only middleware registered *earlier* can catch it. ## What interviewers probe - **Order is registration order**: the first `Use` is the outermost layer on the way in and the last to finish on the way out. - **`Run` vs `Use` that never calls `next`**: both end the pipeline; `Run` states the intent and cannot accidentally delegate. - **Do not write to the body and then call `next`** if a later component may also write or set headers; once the response has started, headers and status code can no longer change. - **The pipeline is built once**, at startup. The lambdas run per request, but the chain of delegates is fixed when the host starts.

  • Which of the two inline app.Use overloads should you prefer, and why?
    The one taking `Func<HttpContext, RequestDelegate, Task>`, where you call `next(context)`. The docs recommend it because the `Func<HttpContext, Func<Task>, Task>` overload has to allocate a closure and a `Func<Task>` on every request to wrap `next`; passing the context through avoids those two allocations.
  • What does the client receive if every middleware calls next and nothing writes a response?
    The builder's own innermost delegate runs: it sets status 404 if the response has not started and marks the request as unhandled. If routing had selected an endpoint that the endpoint middleware never executed, it throws an `InvalidOperationException` instead, telling you to register `UseEndpoints`.
  • In a WebApplication Program.cs, what is the difference between app.Run(handler) and app.Run()?
    `app.Run(handler)` is the `IApplicationBuilder` extension that appends terminal middleware. `app.Run()` is `WebApplication.Run`, which starts the server and blocks until shutdown; it adds nothing to the pipeline and belongs on the last line.

  • app.Run passes the request on to the next middleware after it writes the response.
  • Middleware registered after app.Run still executes for every request.
  • If a Use lambda returns without calling next, ASP.NET Core calls next for it.
  • Earlier middleware stops running its after-next code when a later one short-circuits.
  • app.Run(handler) and app.Run() both start the web server.
open as a page

In ASP.NET Core, how do app.Map, app.MapWhen and app.UseWhen branch the middleware pipeline, and which one rejoins the main pipeline?

level: middleimportance: should knowfreq 50%

basics

~20 s

Map branches on a path prefix and MapWhen on a Func<HttpContext, bool>; both hand the request to a separate pipeline that never returns to the main one. UseWhen also branches on a predicate but rejoins the main pipeline unless the branch short-circuits.

open as a page

In ASP.NET Core 10, a museum audio-guide API registers authentication, authorization and CORS but calls only app.UseCors(); why do rejected calls reach the browser as CORS errors instead of 401s?

level: seniorimportance: should knowfreq 44%

basics

~20 s

WebApplication adds UseAuthentication and UseAuthorization itself, right after its implicit UseRouting and ahead of everything in Program.cs. Authorization therefore rejects requests before UseCors runs, so the 401 carries no CORS headers. Call UseCors, UseAuthentication and UseAuthorization yourself, in that order.

open as a page

In ASP.NET Core, when app.Map("/guide", ...) handles a request for /guide/tours/7, what do Request.PathBase and Request.Path hold inside the branch?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Inside the branch PathBase is the old PathBase plus /guide and Path is /tours/7. Map restores both when the branch returns. Branch code therefore sees paths relative to /guide, while URLs rebuilt from PathBase plus Path still include it.

open as a page