skip to content

Request & Session State

Where an ASP.NET Core app keeps data within one request and across requests: HttpContext items and features, IHttpContextAccessor, ISession and TempData. Interviewers probe what leaks or vanishes.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

10

In ASP.NET Core 10, what does HttpContext carry for one request, and how do Minimal API handlers, controllers and middleware reach it?

level: juniorimportance: must knowfreq 66%

answer

  1. one object per HTTP request
  2. Request, Response, User, Items
  3. RequestServices, RequestAborted, TraceIdentifier
  4. Minimal API: HttpContext parameter
  5. ControllerBase.HttpContext, InvokeAsync(HttpContext)

basics

~20 s

HttpContext is the object ASP.NET Core builds for one HTTP request: Request, Response, User, Items, RequestServices, RequestAborted, TraceIdentifier and the feature collection. Handlers take it as a parameter, controllers read ControllerBase.HttpContext, middleware receive it in InvokeAsync.

solid answer

~40 s

`HttpContext` is the single object that represents one request while it runs through the pipeline. `Request` and `Response` hold the incoming message and the one you write, `User` is the `ClaimsPrincipal` authentication filled in (an empty, unauthenticated principal when nobody signed in, never `null`), `Items` is a per-request dictionary, `RequestServices` is the request's DI scope, `RequestAborted` is a `CancellationToken` for a dropped connection, `TraceIdentifier` is a per-request id, and `Features` exposes server capabilities. A Minimal API handler declares an `HttpContext` (or `HttpRequest`, `HttpResponse`, `ClaimsPrincipal`, `CancellationToken`) parameter, a controller or `PageModel` uses its `HttpContext` property, and middleware receives it as the argument of `InvokeAsync`. It is only valid until the request finishes.

code

csharp · 18 lines
csharp
public class TenantMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context)
    {
        var tenant = context.Request.Headers["X-Tenant"].ToString();
        context.Items["tenant"] = tenant;
        context.Response.Headers["X-Trace"] = context.TraceIdentifier;
        await next(context);
    }
}

[ApiController, Route("invoices")]
public class InvoicesController : ControllerBase
{
    [HttpGet("{id:int}")]
    public IActionResult Get(int id) =>
        Ok(new { id, tenant = HttpContext.Items["tenant"], user = User.Identity?.Name });
}

go deeper

for a junior

Name the main members of HttpContext (Request, Response, User, Items) and show how a Minimal API handler, a controller and a middleware each get hold of it.

for a middle

Explain the less obvious members: RequestServices as the lazily created request scope, RequestAborted, TraceIdentifier versus the trace id, and why User is never null.

for a senior

Stress the lifetime rule: HttpContext is per request, not thread-safe and recycled after the response, so values are copied out before any work outlives the request.

for a principal

Set team conventions for where request data is read: at the edge (handlers, middleware) and passed on as plain values, keeping services free of hidden HttpContext dependencies.

## What HttpContext is Every HTTP request that reaches an ASP.NET Core app is represented by one `HttpContext` object (namespace `Microsoft.AspNetCore.Http`). The server (Kestrel, IIS or HTTP.sys) parses the request, the hosting layer wraps the server's **feature collection** in a `DefaultHttpContext`, and that object is handed to the first middleware. Every middleware, filter and endpoint in the pipeline then works on the **same instance** until the response is complete. ## The members you use every day | Member | Type | What it gives you | |---|---|---| | `Request` | `HttpRequest` | method, path, query, headers, cookies, body, route values | | `Response` | `HttpResponse` | status code, headers, cookies, body stream, `OnStarting` / `OnCompleted` callbacks | | `User` | `ClaimsPrincipal` | the identity authentication established for this request | | `Items` | `IDictionary<object, object?>` | values your own code shares within this request | | `RequestServices` | `IServiceProvider` | the request's DI scope, created on first use | | `RequestAborted` | `CancellationToken` | signals that the connection behind the request was aborted | | `TraceIdentifier` | `string` | a per-request id the server generates | | `Connection` | `ConnectionInfo` | remote and local IP address and port | | `Features` | `IFeatureCollection` | the raw server capabilities everything above is built on | A few details interviewers like to probe: - **`User` is never null.** If no authentication handler signed anyone in, `DefaultHttpContext` returns a `ClaimsPrincipal` wrapping an empty `ClaimsIdentity`, so `User.Identity.IsAuthenticated` is `false` rather than throwing. - **`TraceIdentifier` is not the W3C trace id.** Kestrel builds it from the connection id plus a request counter (HTTP/1.1) or the stream id (HTTP/2). The default ProblemDetails writer puts `Activity.Current?.Id ?? httpContext.TraceIdentifier` into the `traceId` extension, so with an active `Activity` the client sees the distributed trace id instead. - **`RequestServices` is lazy.** The scope is created the first time something reads it and is disposed when the response completes. ## Reaching it from each kind of code 1. **Minimal API handlers** declare it as a parameter. Minimal APIs bind `HttpContext`, `HttpRequest`, `HttpResponse`, `ClaimsPrincipal` and `CancellationToken` parameters straight from the context, without any attribute. 2. **Controllers** (`ControllerBase`) and **Razor Pages** (`PageModel`) expose an `HttpContext` property, plus shortcuts such as `Request`, `Response` and `User`. 3. **Middleware** receives it as the argument of `InvokeAsync(HttpContext context)` (or of the lambda passed to `app.Use`). 4. **Classes outside the pipeline**, such as a repository, can inject `IHttpContextAccessor`, which returns the current context or `null`. In a SaaS invoicing API this looks like: ```csharp app.MapPost("/invoices/{id:int}/send", async ( int id, HttpContext http, ClaimsPrincipal user, CancellationToken ct, InvoiceSender sender) => { var tenant = (string)http.Items["tenant"]!; // set by tenant middleware await sender.SendAsync(tenant, id, user.Identity!.Name!, ct); return Results.Accepted(); }); ``` Here `http`, `user` and `ct` all point at the same request: `user` is `http.User` and `ct` is `http.RequestAborted`. ## Testing code that takes HttpContext Because `HttpContext` is an abstract class with a public default implementation, unit tests do not need a server. `new DefaultHttpContext()` gives a fully working context whose members you can set directly: ```csharp var http = new DefaultHttpContext(); http.Request.Method = "GET"; http.Request.Path = "/invoices/42"; http.Items["tenant"] = "acme"; http.User = new ClaimsPrincipal(new ClaimsIdentity( [new Claim(ClaimTypes.Name, "dana")], "test")); ``` This is one reason to prefer taking `HttpContext` (or better, the plain values you need) as a parameter: the dependency is visible and trivially faked. Integration tests that need the real pipeline use `WebApplicationFactory` instead, which is a different leaf's subject. ## The one rule that matters most `HttpContext` is **valid only while its request is running** and is **not thread-safe**. After the pipeline's `Task` completes, the hosting layer clears and recycles the object for a later request, so code that keeps a reference (a field, a closure in a fire-and-forget task) reads disposed features or another request's data. Copy the values you need (a tenant id, a user id, a header) into ordinary variables before handing work to anything that may outlive the request.

  • In ASP.NET Core, what does HttpContext.User return for an anonymous request?
    A `ClaimsPrincipal` wrapping an empty `ClaimsIdentity`, not `null`. `User.Identity.IsAuthenticated` is `false` and `User.Identity.Name` is `null`, so code can check the flag without a null guard on `User` itself.
  • Why might the traceId in an ASP.NET Core ProblemDetails body differ from HttpContext.TraceIdentifier?
    The default ProblemDetails writer uses `Activity.Current?.Id` first and falls back to `TraceIdentifier` only when no `Activity` is running. With tracing on, the client sees the W3C trace id, while `TraceIdentifier` stays Kestrel's connection-plus-counter id.

  • HttpContext is a static you can read from anywhere, like a global current-request object
  • HttpContext.User is null until authentication succeeds
  • TraceIdentifier is always the same value as the W3C trace id
  • A Minimal API handler needs [FromServices] to receive HttpContext
  • Keeping HttpContext in a field after the request is harmless
open as a page

In ASP.NET Core 10, what must Program.cs register to use HttpContext.Session, and how does a handler store and read a value?

level: juniorimportance: must knowfreq 58%

basics

~20 s

Session needs an IDistributedCache (AddDistributedMemoryCache on one instance), AddSession and app.UseSession before the endpoints that use it. Handlers call HttpContext.Session.SetString or SetInt32 and GetString or GetInt32; ISession stores byte arrays, so objects are serialized first.

open as a page

In ASP.NET Core 10, how does IHttpContextAccessor find the current request, and what does injecting it into a service cost?

level: middleimportance: must knowfreq 58%

basics

~20 s

AddHttpContextAccessor registers a singleton HttpContextAccessor that keeps the current HttpContext in a static AsyncLocal, set when the request starts and cleared when it ends. It returns null outside a request and hides a request dependency inside the service.

open as a page

In ASP.NET Core MVC or Razor Pages, when does a TempData value survive into the next request, and how do Keep and Peek change that?

level: middleimportance: must knowfreq 50%

basics

~20 s

TempData keeps a value until a request reads it; at the end of that request read keys are removed and unread keys are saved again. Peek(key) reads without marking, Keep(key) or Keep() retains read values, and redirect results call Keep() automatically.

open as a page

In ASP.NET Core, how do HttpContext.Items and HttpContext.Features differ, and when would you reach for each one?

level: middleimportance: should knowfreq 45%

basics

~10 s

Items is an IDictionary<object, object?> for your own per-request values. Features is an IFeatureCollection keyed by interface type, through which the server and middleware expose capabilities such as IHttpRequestFeature, IHttpConnectionFeature or IHttpMaxRequestBodySizeFeature.

open as a page

In an ASP.NET Core 10 API, what is HttpContext.RequestAborted, how does a handler get it, and when should work ignore it?

level: middleimportance: should knowfreq 48%

basics

~20 s

RequestAborted is a CancellationToken that fires when the connection behind the request is aborted, by a client disconnect or HttpContext.Abort(). Handlers receive it as a CancellationToken parameter and pass it to I/O; work that must complete should not use it.

open as a page

In ASP.NET Core 10, what do SessionOptions.IdleTimeout, IOTimeout and Cookie default to, and what does IdleTimeout actually expire?

level: middleimportance: should knowfreq 40%

basics

~20 s

IdleTimeout defaults to 20 minutes and is a sliding expiration on the server-side record, not on the cookie. IOTimeout (1 minute) bounds async store calls. The .AspNetCore.Session cookie is a browser-session cookie: HttpOnly, SameSite Lax, not essential.

open as a page

An ASP.NET Core 10 invoicing API reads the tenant from HttpContext inside a Task.Run started by a handler; why does it intermittently throw or read the wrong tenant?

level: seniorimportance: should knowfreq 40%

basics

~20 s

HttpContext lives only until the request's pipeline Task completes; then it is cleared and Kestrel reuses the same object for the next request on that connection. Late reads throw ObjectDisposedException, return null through the accessor, or see another request's tenant.

open as a page

Why does an ASP.NET Core 10 mortgage pre-approval wizard that keeps its steps in session lose answers after scaling to three instances, with two browser tabs overwriting each other?

level: seniorimportance: should knowfreq 36%

basics

~20 s

An in-memory IDistributedCache is per instance and an unshared Data Protection key ring makes the session cookie unreadable elsewhere, so other instances see an empty session. Session is non-locking and saved whole, so the last request to commit wins.

open as a page

In ASP.NET Core 10 MVC, how do the cookie and session TempData providers differ, and when would you switch to AddSessionStateTempDataProvider?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

CookieTempDataProvider, the default, stores TempData in a Data Protection-encrypted, chunked cookie, so no server state is needed. SessionStateTempDataProvider, enabled by AddSessionStateTempDataProvider, stores it in ISession and needs session configured; it avoids sending large TempData on every request.

open as a page