Skip to content

5.8 — HttpContext

← Roadmap · Section: 5. Middleware and the Request Pipeline Prev: 5.7 Short-circuiting · Next: 5.9 Request body buffering

Markers: 🔥 · Confidence: 🔴 · Last reviewed: —


TL;DR

HttpContext is the object holding everything about one HTTP request and its response. Every middleware, filter and action receives it.

  • One instance per request. It is created when the request arrives and disposed when the response completes.
  • It is not thread-safe, and storing it anywhere is a bug.
  • The parts you use daily: Request, Response, Items, User, RequestServices, RequestAborted.

Definitions

Term What it is What it means
HttpContext an abstract class Everything about one request and response. Created per request.
Request a property (HttpRequest) Incoming data — path, method, headers, query string, body.
Response a property (HttpResponse) Outgoing data — status code, headers, body.
Items a property (IDictionary<object, object>) A scratchpad for passing data between middleware within one request.
User a property (ClaimsPrincipal) Who the caller is. Populated by UseAuthentication. Never null, but may be unauthenticated.
RequestServices a property (IServiceProvider) The request-scoped DI container.
RequestAborted a property (CancellationToken) Fires when the client disconnects.
Features a property (IFeatureCollection) Low-level server capabilities. The extensibility mechanism underneath everything.
Connection a property Remote IP address, port, client certificate.
TraceIdentifier a property (string) A per-request ID the framework generates. Useful in error responses.
Response.HasStarted a property (bool) Whether any bytes have been sent. Once true, headers are immutable.
OnStarting a method Registers a callback to run just before the first byte is written.
IHttpContextAccessor an interface Reaches the current context outside a controller. Use sparingly — see 21.12.

The concept

One object, one request

When a request arrives, ASP.NET Core creates one HttpContext and passes the same instance through every middleware, then to the filter pipeline and finally your action. When the response finishes, it is disposed and often pooled for reuse.

That last detail matters more than it sounds — see the trap section.

A picture: a job docket travelling through a workshop. Everyone who touches the job writes on the same docket. It carries the original order, notes added along the way, and eventually the finished result. When the job ships, the docket is filed and the clipboard reused for the next job.

What replaced HttpContext.Current

Classic ASP.NET had a static HttpContext.Current reachable from anywhere. Convenient, and a genuine design flaw — it made code untestable and coupled every layer to the web (4.1).

ASP.NET Core has no static context. You receive it as a parameter, which means a method's dependencies are visible in its signature and it can be tested with a DefaultHttpContext.


How it works

The simple version — the parts you use

public async Task InvokeAsync(HttpContext context)
{
    // ── the request ──
    context.Request.Method;                    // "GET"
    context.Request.Path;                      // "/api/orders/42"
    context.Request.QueryString;               // "?page=2"
    context.Request.Query["page"];             // "2"
    context.Request.Headers["Authorization"];
    context.Request.ContentType;
    context.Request.Body;                      // a Stream — see 5.9

    // ── the response ──
    context.Response.StatusCode = 200;
    context.Response.Headers["X-Custom"] = "value";
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsJsonAsync(new { ok = true });

    // ── the caller ──
    context.User.Identity?.IsAuthenticated;    // bool
    context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
    context.Connection.RemoteIpAddress;

    // ── infrastructure ──
    context.RequestServices.GetRequiredService<IOrderService>();
    context.RequestAborted;                    // client-disconnect token
    context.TraceIdentifier;                   // "0HN7B1..." per-request id
    context.Items["key"] = value;              // scratchpad
}

Items — passing data down the pipeline

Items is a dictionary scoped to one request. It is how middleware hands information to code further down:

// Early middleware writes
app.Use(async (context, next) =>
{
    context.Items["CorrelationId"] = Guid.NewGuid().ToString();
    await next();
});

// A controller reads
public IActionResult Get()
{
    var correlationId = HttpContext.Items["CorrelationId"] as string;
    return Ok(new { correlationId });
}

⚠️ It is untyped and stringly-keyed, so a typo gives you null rather than a compile error. Use a constant for the key, or a typed wrapper:

public static class HttpContextExtensions
{
    private const string CorrelationIdKey = "__CorrelationId";

    public static void SetCorrelationId(this HttpContext ctx, string id)
        => ctx.Items[CorrelationIdKey] = id;

    public static string? GetCorrelationId(this HttpContext ctx)
        => ctx.Items[CorrelationIdKey] as string;
}

Prefer a scoped service for anything substantial. A scoped service is typed, injectable and testable; Items is right for small, incidental values that only middleware cares about.

⚠️ HasStarted — the response is one-way

The single most common HttpContext error:

await next(context);

context.Response.Headers["X-Duration"] = "42ms";
// ✗ InvalidOperationException:
//   "Headers are read-only, response has already started."

HTTP sends headers before the body. Once any byte of body has gone out, the headers are on the wire and cannot change. Same for the status code.

Two fixes:

// 1. Check first
await next(context);
if (!context.Response.HasStarted)
    context.Response.Headers["X-Duration"] = "42ms";
// 2. Better — register a callback that runs just before the first byte
context.Response.OnStarting(() =>
{
    context.Response.Headers["X-Duration"] = $"{sw.ElapsedMilliseconds}ms";
    return Task.CompletedTask;
});

await next(context);        // register BEFORE calling next

OnStarting is the correct answer when you need to set a header based on work done during the request. Register it before next, so it is in place before anything downstream writes.

The deeper detail — Features

HttpContext is a friendly facade over a feature collection — a set of interfaces the server implements. Request and Response are convenience wrappers over those features.

// Ask the server whether it supports a capability
var bodyFeature = context.Features.Get<IHttpRequestBodyDetectionFeature>();
var syncIo = context.Features.Get<IHttpBodyControlFeature>();

if (syncIo is not null)
    syncIo.AllowSynchronousIO = true;      // off by default, for good reason

This design is why the same HttpContext works over Kestrel, IIS and HTTP.sys — each server supplies its own feature implementations, and code asks for a capability rather than assuming it. It is rare to touch directly, but knowing it exists explains a lot of the framework's extensibility.

AllowSynchronousIO is the feature you are most likely to meet. Synchronous reads and writes are disabled by default because they block a thread-pool thread (2.13). If a library throws "Synchronous operations are disallowed", that is why — and enabling it is a workaround, not a fix.

⚠️ Never store HttpContext

// ✗ CATASTROPHIC
public class BadService
{
    private static HttpContext? _context;

    public void Remember(HttpContext ctx) => _context = ctx;
}

Two reasons this breaks badly:

It is not thread-safe. One instance belongs to one request on one execution flow.

It is pooled and reused. After the response completes, the framework may reset the object and hand it to a different request. Your stored reference now points at someone else's request — potentially exposing one user's data to another. That is a security bug, not just a correctness one.

The same applies to capturing it in a background task:

// ✗ WRONG — the request may finish before this runs
_ = Task.Run(async () =>
{
    await DoWorkAsync(context.User.Identity!.Name);   // context may be recycled
});

// ✓ Copy the values you need FIRST
var userName = context.User.Identity?.Name;
_ = Task.Run(async () => await DoWorkAsync(userName));

And in ASP.NET Core, fire-and-forget from a request is usually the wrong pattern anyway — 2.15 and 21.1.


Code

A middleware using the pieces properly:

internal class RequestContextMiddleware(
    RequestDelegate next,
    ILogger<RequestContextMiddleware> logger)
{
    public async Task InvokeAsync(HttpContext context)
    {
        // Prefer an incoming correlation id so traces span services
        var correlationId = context.Request.Headers["X-Correlation-Id"].FirstOrDefault()
                            ?? context.TraceIdentifier;

        context.Items["CorrelationId"] = correlationId;

        // Register BEFORE next, so it is in place before the response starts
        context.Response.OnStarting(() =>
        {
            context.Response.Headers["X-Correlation-Id"] = correlationId;
            return Task.CompletedTask;
        });

        using (logger.BeginScope(new Dictionary<string, object>
        {
            ["CorrelationId"] = correlationId,
            ["UserId"] = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous",
            ["ClientIp"] = context.Connection.RemoteIpAddress?.ToString() ?? "unknown"
        }))
        {
            await next(context);
        }
    }
}

Every log line written anywhere downstream now carries the correlation ID, user and client IP, with no extra code in your controllers — 18.4.

Testing with DefaultHttpContext

var context = new DefaultHttpContext();
context.Request.Path = "/api/orders";
context.Request.Method = "GET";
context.Request.Headers["X-Api-Key"] = "test-key";
context.Response.Body = new MemoryStream();       // capture what gets written

context.User = new ClaimsPrincipal(new ClaimsIdentity(
    [new Claim(ClaimTypes.NameIdentifier, "user-1")],
    authenticationType: "Test"));                 // ← makes IsAuthenticated true

⚠️ That authenticationType argument matters. A ClaimsIdentity created without one has IsAuthenticated == false, so [Authorize] still rejects it — a common source of confusing test failures.


Interview questions

Q: What is HttpContext?

It is the object holding everything about a single HTTP request and its response — the path, method, headers and body coming in, the status code and body going out, the authenticated user, the request-scoped DI container, and a cancellation token that fires if the client disconnects. One instance is created per request and passed through every middleware, filter and action. It replaced classic ASP.NET's static HttpContext.Current, which was convenient but made code untestable and coupled every layer to the web.

Q: Why can't you set a response header after calling next?

Because HTTP sends headers before the body, so once any byte of the body has been written the headers are already on the wire and immutable — attempting to change them throws. You can guard with Response.HasStarted, but the better answer is Response.OnStarting, which registers a callback that runs immediately before the first byte is sent. You register it before calling next, so it is in place before anything downstream starts writing, and it can then set headers based on work measured during the request.

Q: Why must you never store an HttpContext?

Two reasons. It is not thread-safe — one instance belongs to one request on one execution flow. More seriously, the framework pools and reuses these objects: after a response completes it may be reset and handed to a different request, so a stored reference ends up pointing at someone else's request. That is a security problem, not just a correctness one, because you could read another user's data. If you need values in a background task, copy the primitives you need before starting it.

Q: What is HttpContext.Items for, and when would you use something else?

It is a dictionary scoped to one request, used to pass small pieces of data from middleware to code further down the pipeline — a correlation ID, a resolved tenant. Its weakness is that it is untyped and keyed by string, so a typo gives you null rather than a compile error. For anything substantial I would use a scoped service instead, which is typed, injectable and testable. Items earns its place for incidental values that only the pipeline cares about.


Traps ⚠️

  • Storing HttpContext anywhere. It is pooled and reused — you may end up reading another user's request.
  • Setting headers or status after the response has started throws. Use OnStarting.
  • Items is untyped and string-keyed. Typos fail silently. Use constants or a typed wrapper.
  • context.User is never null but may be unauthenticated. Check User.Identity?.IsAuthenticated.
  • A ClaimsIdentity with no authenticationType is not authenticated, which breaks tests in confusing ways.
  • Request.Body can only be read once unless you enable buffering — see 5.9.
  • Synchronous IO is disabled by default. Enabling AllowSynchronousIO is a workaround, not a fix.
  • Capturing the context in a fire-and-forget task races with the request completing.


Sources