SkillPilotAI

The middleware pipeline

Middleware are the steps a request passes through between reaching the server and the response being sent. Together they form the middleware pipeline, and its order decides what runs, what is skipped and what can short circuit the request.

41.1 Why is it used?

  • Cross-cutting work (API key checks, timing, logging, correlation ids, error handling) is written once instead of in every endpoint.
  • Every middleware sees both the request (on the way in) and the response (on the way out).
  • A middleware can stop a bad request early (short circuit) so the endpoint never runs.
  • ASP.NET Core features themselves (HTTPS redirection, static files, authentication, authorization, routing) are middleware.

41.2 The bug: the key check never ran

C#
var app = WebApplication.Create(args); app.Run(context =>    context.Response.WriteAsync("3 orders")); app.Use(async (context, next) =>{    var headers = context.Request.Headers;    if (headers["X-Api-Key"] == "secret-123")        await next(context);    else        context.Response.StatusCode = 401;}); app.Run();
Output
$ curl -i localhost:5041/ordersHTTP/1.1 200 OKServer: KestrelTransfer-Encoding: chunked 3 orders
  • Middleware runs in exactly the order you register it.
  • Run is terminal: it never gets a next step, so the request ends there and the response goes back.
  • Any middleware written after Run never executes, so the security check was silently skipped (200 OK and 3 orders without a key).
Why the key check was skipped
  1. 1.Register order = run order

  2. 2.Run comes first and writes "3 orders"

  3. 3.Run is terminal: no next

  4. 4.Use (key check) after Run never runs

Middleware after Run is dead code

41.3 Fix: Use before Run

C#
var app = WebApplication.Create(args); app.Use(async (context, next) =>{    var headers = context.Request.Headers;    if (headers["X-Api-Key"] == "secret-123")        await next(context);    else        context.Response.StatusCode = 401;}); app.Run(context =>    context.Response.WriteAsync("3 orders")); app.Run();
Output
$ curl -i localhost:5041/ordersHTTP/1.1 401 UnauthorizedContent-Length: 0Server: Kestrel $ curl -i localhost:5041/orders \  -H "X-Api-Key: secret-123"HTTP/1.1 200 OKServer: Kestrel 3 orders
  • Use gets two things: context (the current request) and next (the next step of the pipeline).
  • Correct key: await next(context) passes the request on.
  • Wrong or missing key: StatusCode = 401 and next is not called, so the request goes no further. This is a short circuit.

41.4 Use: code before and after next

C#
var app = WebApplication.Create(args);var clock = TimeProvider.System; app.Use(async (context, next) =>{    var start = clock.GetTimestamp();    await next(context);    var ms = clock.GetElapsedTime(start);    Console.WriteLine($"{context.Request.Path} " +        $"{context.Response.StatusCode} " +        $"{ms.TotalMilliseconds:F1} ms");}); app.MapGet("/orders", () => "3 orders");app.Run();
Output
$ dotnet run --urls http://localhost:5041info: Microsoft.Hosting.Lifetime[14]      Now listening on: http://localhost:5041/orders 200 8.2 ms/orders 200 0.2 ms
  • Code before await next runs on the way in (start time).
  • await next runs the rest of the pipeline and the endpoint.
  • Code after it runs on the way back (elapsed time, path, status code).
  • The first request is slower (8.2 ms vs 0.2 ms) because of warm up.
Pipeline: a two way road
  1. 1.Request in: A -> B -> endpoint

  2. 2.Endpoint builds the response

  3. 3.Response out: B -> A (reverse order)

  4. 4.Any middleware that skips next = short circuit, stop here

Registration decides the order

41.5 Checkpoint: what gets printed?

C#
app.Use(async (context, next) =>{    Console.WriteLine("A in");    await next(context);    Console.WriteLine("A out");});app.Use(async (context, next) =>{    Console.WriteLine("B in");    await next(context);    Console.WriteLine("B out");});app.Run(context =>    context.Response.WriteAsync("Done"));
Output
$ curl localhost:5041/Done# server consoleA inB inB outA out
  • On the way in A runs first, on the way back B finishes first: A in, B in, B out, A out.

41.6 Use, Run and Map

C#
var app = WebApplication.Create(args);app.Map("/admin", admin =>{    admin.Use(async (context, next) =>    {        Console.WriteLine("Admin branch");        await next(context);    });    admin.Run(context =>        context.Response.WriteAsync(            $"Admin: {context.Request.Path}"));}); app.MapGet("/orders", () => "3 orders");app.Run();
Output
$ curl localhost:5041/admin/usersAdmin: /users# server console: Admin branch $ curl localhost:5041/orders3 orders
  • Map("/admin", ...) sends every request starting with /admin into a separate mini pipeline with its own Use and Run.
  • Inside the branch the matched prefix is removed from Request.Path, so /admin/users prints only /users.
  • Other requests (/orders) stay in the main pipeline.
MethodCalls next?What it does
UseYes (optional)Runs code before/after next; can short circuit by not calling next
RunNo (terminal)Ends the pipeline and writes the response; anything after it never runs
MapBranchesCreates a separate pipeline for a path prefix; prefix is stripped from Path
UseMiddleware<T>YesRegisters a middleware class with InvokeAsync

41.7 Custom middleware class

C#
public class CorrelationIdMiddleware(    RequestDelegate next){    public async Task InvokeAsync(        HttpContext context)    {        var id = Guid.NewGuid().ToString()[..8];        context.Items["CorrelationId"] = id;        context.Response.Headers            ["X-Correlation-Id"] = id;        await next(context);    }}
  • In real projects middleware goes in a class so it is reusable and testable.
  • The constructor gets a RequestDelegate (the next step); InvokeAsync runs for every request.
  • The id is stored in HttpContext.Items and also put in a response header, before next (headers must be set before the response starts).

41.8 HttpContext: Request, Items, User

C#
var app = WebApplication.Create(args);app.UseMiddleware<CorrelationIdMiddleware>(); app.MapGet("/orders", (HttpContext context) =>{    var id = context.Items["CorrelationId"];    var city = context.Request.Query["city"];    var user = context.User.Identity?.Name        ?? "guest";    return $"{id}: orders for {user} in {city}";}); app.Run();
Output
$ curl -i "localhost:5041/orders?city=Pune"HTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8X-Correlation-Id: ca16be1e ca16be1e: orders for guest in Pune
  • UseMiddleware<CorrelationIdMiddleware>() registers the class; .NET fills constructor dependencies from DI.
  • HttpContext holds everything about one request.
  • Items is a dictionary that lives only for this one request, so the endpoint reads the same id the middleware stored.
  • Request.Query["city"] reads the query string; User.Identity?.Name is the logged in user (guest here, no authentication yet).

41.9 Common mistakes

  • Registering Use after Run: it never runs.
  • Setting a header after await next: the response has already started, so the server throws InvalidOperationException (headers are read-only).
  • Myth: a Use written after MapGet runs after the endpoint. WebApplication puts endpoints at the end of the pipeline, so the output is middleware in -> endpoint -> middleware out. Run's position, however, does matter.
  • Injecting scoped services in a middleware class constructor: the class is created only once, so take scoped services as InvokeAsync parameters.

Wrong: header after next.

C#
app.Use(async (context, next) =>{    var start = clock.GetTimestamp();    await next(context);    var ms = clock.GetElapsedTime(start);    context.Response.Headers["X-Response-Ms"] =        ms.TotalMilliseconds.ToString("F1");});// InvalidOperationException: Headers are// read-only, response has already started.

Right: OnStarting registers a callback that runs just before the headers are sent.

C#
app.Use(async (context, next) =>{    var start = clock.GetTimestamp();    context.Response.OnStarting(() =>    {        var ms = clock.GetElapsedTime(start);        context.Response.Headers["X-Response-Ms"]            = ms.TotalMilliseconds.ToString("F1");        return Task.CompletedTask;    });    await next(context);});// X-Response-Ms: 7.4

41.10 Middleware rules

  1. Order: exception handling -> HTTPS -> static files -> authentication/authorization -> endpoints.
  2. Use Run only at the end of the pipeline.
  3. Set headers before next or inside OnStarting.
  4. Put reusable logic in a middleware class.
  5. Scoped services go in InvokeAsync parameters, not the constructor.
Typical production order
  1. 1.UseExceptionHandler (catches everything below)

  2. 2.UseHttpsRedirection

  3. 3.UseStaticFiles

  4. 4.UseAuthentication -> UseAuthorization

  5. 5.Endpoints (MapGet / controllers)

Errors at the top, endpoints at the end

41.11 Interview tips

  • Middleware is a component that handles both the request and the response; together they form a pipeline that runs in registration order.
  • Use passes the request on by calling next, Run is terminal, Map creates a branch by path.
  • The response passes back through middleware in reverse order; not calling next is a short circuit.
  • Reusable middleware is a class with InvokeAsync registered with UseMiddleware; set headers before the response starts (or in OnStarting).