Skip to the workspace
Pebellslearn by building
ASP.NET Core Basics: Pipeline, Services and Settings  ›  Lesson

Middleware — The Request Pipeline

Middlewares 15 minMiddleware components form a chain in registration order, and each one can act on the request, pass it on, and act on the response on the way back.

aspnet core / Middleware — The Request Pipeline

Explore each scene at your own pace.

01 · The rule

The rule

Middleware — The Request Pipeline

Before a ReadingRoom endpoint sees a request, it has already been redirected to HTTPS, had its login token checked, and been timed. Each of those jobs is a middleware: a small piece of code in a chain. Get the chain's order wrong and security checks quietly stop working.

The rule

Registered order is running order: in on the way down, out on the way back.

Every app.Use... call in Program.cs adds one link to the pipeline. A request walks down the chain, reaches an endpoint, and the response walks back up through the same links in reverse.

var app = builder.Build();

app.UseExceptionHandler("/error");  // 1. catches anything thrown below it
app.Use(async (context, next) =>    // 2. custom: time every request
{
    var started = Stopwatch.GetTimestamp();
    await next(context);            //    everything below runs here
    var ms = Stopwatch.GetElapsedTime(started).TotalMilliseconds;
    context.RequestServices.GetRequiredService<ILogger<Program>>()
        .LogInformation("{Path} took {Ms} ms", context.Request.Path, ms);
});
app.UseHttpsRedirection();          // 3. send http:// visitors to https://
app.UseAuthentication();            // 4. who is this?
app.UseAuthorization();             // 5. may they do this?
app.MapControllers();               // 6. the endpoints
app.Run();

Code before await next(context) runs on the way in; code after it runs on the way out. A middleware that does not call next short-circuits: it writes the response itself and nothing further down runs. That is how UseHttpsRedirection answers with a redirect, or how UseStaticFiles serves a file without touching your endpoints.

Endpoints themselves (MapControllers, MapGet) always run at the bottom of the chain, after every Use... call. Built-in middleware covers most needs: exception handling, HTTPS redirection, static files, routing, CORS, authentication, authorization, rate limiting and response compression.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.