Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 52 ยท Middleware and the Request Pipeline

HttpContext, Request and Response

Explore HttpContext in ASP.NET Core: request properties, headers, query strings, Items, features, reading bodies twice and the rules for when a response has started.

Every request that Kestrel accepts becomes one HttpContext object. It is the single bag that middleware and endpoints share: it holds the incoming Request, the outgoing Response, the authenticated User, the per-request service container, a dictionary for passing data along the pipeline and a low-level collection of features. When a minimal API lambda asks for HttpContext context, this is what it receives.

You have already used pieces of it in the middleware pipeline and custom middleware lessons. This lesson slows down and tours the object properly: what each property means, how to read headers and bodies safely, how to pass data between components and, most importantly, the rules about when a response can still be changed. Breaking that last rule is one of the most common runtime errors in real middleware.

What is inside HttpContext

flowchart TB
    HC["HttpContext"] --> RQ["Request<br/>method, path, query,<br/>headers, body"]
    HC --> RS["Response<br/>status, headers, body"]
    HC --> US["User<br/>ClaimsPrincipal"]
    HC --> IT["Items<br/>per-request dictionary"]
    HC --> RSV["RequestServices<br/>scoped container"]
    HC --> FT["Features<br/>low-level server data"]
    HC --> CN["Connection<br/>remote and local address"]
    HC --> RA["RequestAborted<br/>CancellationToken"]

One HttpContext lives for exactly one request and is thrown away afterwards.

The most useful members:

Member Meaning
Request The incoming HTTP message.
Response The outgoing HTTP message you are building.
User A ClaimsPrincipal; anonymous until authentication runs.
Items A dictionary that lives as long as the request.
RequestServices The scoped IServiceProvider for this request (see dependency injection).
RequestAborted A CancellationToken that fires when the client disconnects.
Connection Remote and local IP addresses and ports.
Features The raw feature collection the server filled in.
TraceIdentifier A string id for this request, handy in logs and error responses.

An HttpContext is not thread-safe and must not be stored in a field or used after the request ends. If background work needs a value from the request, copy the value out first.

The request

HttpRequest exposes the parts of the HTTP message as typed properties, so you rarely need to parse text yourself.

Property Example value Notes
Method POST A string; compare with HttpMethods.IsPost(...).
Scheme http Reflects forwarded headers when configured.
Host HostString Has Host and Port parts.
PathBase empty or /app Where the app is mounted.
Path /inspect/42 The part after PathBase.
QueryString ?tag=a&tag=b The raw text.
Query collection Parsed; each key maps to a StringValues.
Headers collection Case-insensitive keys, StringValues values.
ContentType, ContentLength application/json, 17 Shortcuts for common headers.
Protocol HTTP/1.1 Or HTTP/2, HTTP/3.
RouteValues id = 42 Filled in by routing.
Body Stream Forward-only by default.

StringValues is a small struct that represents zero, one or many strings without allocating for the common single-value case. It converts implicitly to string (joining many values with commas) and to string[]. Because HTTP allows repeated headers and repeated query keys, this is the honest type for them.

C# Reading everything a request carries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the missing key: Query["nope"] does not throw. It returns an empty StringValues, which prints as an empty string. Use .Count or TryGetValue when you need to tell "absent" from "empty".

In minimal APIs you rarely read Request.Query by hand because parameter binding does it for you. Reach for the raw request when you need every header, a streaming body or something binding cannot express.

Reading the body

Request.Body is a forward-only stream that Kestrel reads from the network as you consume it. Two consequences follow:

  1. You can read it once. A second ReadToEndAsync() returns an empty string, because the stream is already at the end.
  2. If a middleware reads the body, an endpoint later in the pipeline sees nothing (and model binding fails or finds an empty body).

When several components need the body, call Request.EnableBuffering() first. It replaces the stream with one that can be rewound (buffering small bodies in memory and large ones on disk). After reading, set Position = 0 so the next reader starts at the beginning. Always leave the stream where you found it.

C# Reading a body once, then twice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Buffering has a cost: memory or disk for every request that uses it. Enable it only on the routes that need it (for example an audit-logging middleware for one prefix), and never read an unbounded body into a string. Kestrel's MaxRequestBodySize default of about 28.6 MB is a safety net, not a design target.

Items: passing data down the pipeline

context.Items is an IDictionary<object, object?> that exists for one request. Middleware early in the chain can store a value and later middleware or endpoints can read it. Use it for things like a correlation id, a tenant resolved from the host name or a parsed API key.

Keys are object, so a plain string works, but a private static readonly object or a typed key class avoids collisions between libraries. A common alternative is to wrap the value in a small scoped service, which is easier to test; Items is the lightweight option.

Features: the layer under the properties

HttpRequest and HttpResponse are friendly wrappers. Underneath, the server fills context.Features with small interfaces such as IHttpRequestFeature, IHttpResponseFeature, IHttpConnectionFeature and IHttpMaxRequestBodySizeFeature. Get<T>() returns the feature or null, so you can ask whether the current server supports something before using it.

You seldom need features directly. They matter when you tune per-request limits, enable response-body options or write a server or test host of your own.

C# Items, a feature and the cancellation token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

RequestAborted is worth remembering: pass it to database calls and HttpClient requests so that work stops when the browser tab is closed. Minimal API handlers can simply declare a CancellationToken parameter to get the same token.

The response and the "has started" rule

An HTTP response has a strict order: status line, headers, then body. Once the first byte of the body leaves the server, the status and headers have already been sent and cannot be taken back. ASP.NET Core models this with Response.HasStarted.

flowchart LR
    A["Set status<br/>and headers"] --> B["First write<br/>to Body"]
    B --> C["HasStarted = true"]
    C --> D["More body bytes"]
    A -. "allowed" .-> A
    C -. "status and headers<br/>are now read-only" .-> C

Before the first body write you may change the status and headers freely; afterwards, doing so throws an exception.

What counts as "started"?

  • Writing to Response.Body (including WriteAsync and await Response.StartAsync()), and anything that flushes it.
  • Returning a result that writes a body; the framework does this after your lambda returns.

Typical consequences:

  • Setting a header after writing the body throws InvalidOperationException ("Headers are read-only, response has already started").
  • Setting StatusCode after the start throws as well.
  • Exception handlers can no longer produce a clean error page once the response has started (the error handling lesson shows what to do), because the 200 status is already on the wire.

Two tools help you cope:

  • Response.OnStarting(callback) runs just before the headers are sent. It is the right place to add headers such as X-Response-Time or security headers after the endpoint has finished, because you know the response is about to start but has not.
  • Response.OnCompleted(callback) runs after the response is sent; use it for logging and cleanup, never to change the response.
C# OnStarting and the has-started rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the notes at the end in order. In /normal, HasStarted flips to true after the first write. In /late-header, the attempt to add a header throws, and the client never sees the header. Our try/catch caught the exception, but in real code you would avoid the situation by deciding headers before writing, or by using OnStarting.

Writing responses by hand

Most of the time you return values or Results, as the responses lesson explains. Writing straight to Response is the low-level path and is useful for streaming:

  • Response.WriteAsync(string) writes text using the response encoding.
  • Response.WriteAsJsonAsync(value) serializes JSON and sets the content type.
  • Response.Body is a Stream; Response.BodyWriter is a PipeWriter for high-throughput code.
  • Set Response.ContentType and, when known, Response.ContentLength before the first write. Without a length, Kestrel uses chunked transfer encoding.

Always pass context.RequestAborted to long loops that write, so that a disconnected client stops the work.

Common mistakes

  • Reading the body in middleware and forgetting to rewind it, which breaks binding downstream.
  • Mutating headers after next() returns in middleware. The endpoint has usually already started the response by then. Use OnStarting instead.
  • Capturing HttpContext in a background task. The object is recycled after the request. Copy the values you need.
  • Using Request.Query["x"] as if it were a string. It is StringValues; repeated keys give several values.
  • Assuming Host is trustworthy. It comes from the client; validate it, or configure allowed hosts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Request.Query["missing"] return when the key is absent?

    The query collection never throws for a missing key. You get an empty StringValues, so check Count or use TryGetValue to tell absent from empty.
  2. 2. A middleware reads the whole request body with a StreamReader and calls next(). Why might the endpoint then fail to bind the body?

    Without EnableBuffering() the body can be read only once. Buffer it and set Position = 0 after reading so the next component can read it again.
  3. 3. When does Response.HasStarted become true?

    HasStarted means the status line and headers have been committed. After that the status code and headers are read-only.
  4. 4. Where is the safest place to add a header based on what the endpoint did?

    OnStarting runs just before the headers go out, so the change is still allowed. OnCompleted runs after the response is sent and is too late to change it.
  5. 5. Why should you avoid storing HttpContext in a field and using it from a background task?

    The context is tied to a single request and is recycled afterwards. Copy the values you need (ids, claims, headers) before starting background work.

Summary

  • HttpContext is one object per request that carries Request, Response, User, Items, RequestServices, Features and RequestAborted.
  • Headers and query values are StringValues, because HTTP allows repeats; missing keys give an empty value, not an exception.
  • Request.Body is forward-only: use EnableBuffering() and reset Position when more than one component reads it.
  • Items passes per-request data down the pipeline; Features expose the low-level server layer.
  • Once Response.HasStarted is true, the status code and headers cannot change; use OnStarting for last-moment headers and OnCompleted for after-send work.
  • Never keep an HttpContext beyond its request, and pass RequestAborted to long operations.

Next: Error Handling and Problem Details