.NET › ASP.NET Core Middleware & Request Pipeline

How does the HttpContext object serve as the shared state carrier through the middleware pipeline?

Intermediate

Answer

HttpContext encapsulates everything about a single HTTP request/response cycle -- the request (headers, body, route values), the response (status code, headers, body stream), user identity (once authentication runs), and a Items dictionary for passing arbitrary custom data between middleware components within the same request's lifetime, since each middleware receives the same HttpContext instance as the pipeline executes.
app.Use(async (context, next) => {
    context.Items["RequestStartTime"] = DateTime.UtcNow;  // stash data for later middleware
    await next();
});

app.Use(async (context, next) => {
    var start = (DateTime)context.Items["RequestStartTime"];
    Console.WriteLine($"Elapsed: {DateTime.UtcNow - start}");
    await next();
});
Real-world example A correlation-ID middleware generates a unique ID early in the pipeline, stores it in context.Items, and every subsequent logging call throughout the request (including deep inside business logic) retrieves it via HttpContext to tag all related log entries consistently.

Common follow-ups: How does HttpContext.Items differ from HttpContext.Features for passing data?;Why shouldn't you store HttpContext itself in a singleton service?