Lesson 13 / 26

The Middleware Pipeline

Understand middleware order and write a small custom middleware.

A chain of steps

Each middleware can run code before and after the next one by calling next(). Order matters: the order in Program.cs is the order requests travel, and the reverse for responses.

Inline timing middleware

This measures how long the rest of the pipeline takes and logs it. Code after await next() runs on the way back.

app.Use(async (context, next) =>
{
    var sw = System.Diagnostics.Stopwatch.StartNew();
    await next();
    sw.Stop();
    app.Logger.LogInformation("{Path} took {Ms} ms", context.Request.Path, sw.ElapsedMilliseconds);
});

Airport security checks

Passengers pass ID check, baggage scan, then boarding, and leave in the reverse flow. A middleware that rejects early, like a failed ID check, stops the request from reaching later steps.

Quick check: What happens if a middleware never calls next()?

  • The request is short-circuited there
  • The server restarts
  • The next middleware runs twice
  • The app fails to compile
Answer

The request is short-circuited there — Not calling `next()` short-circuits the pipeline; later middleware and the endpoint never run.