# The Middleware Pipeline — .NET Core: Build, Test and Ship Web APIs

Source: https://www.geekswithgeeks.com/en/dotnet-core/api-middleware

> 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.

```csharp
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.

**Quiz:** What happens if a middleware never calls next()?

- [x] 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.
