In ASP.NET Core, how do HttpContext.Items and HttpContext.Features differ, and when would you reach for each one?
answer
- your data vs server capabilities
- IDictionary<object, object?> vs IFeatureCollection
- keyed by object vs keyed by interface Type
- Features.Get<T>() returns null if missing
- IHttpMaxRequestBodySizeFeature, IHttpConnectionFeature
basics
~10 sItems 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.
solid answer
~40 s`HttpContext.Items` is an application-level bag: middleware stores a resolved tenant or a stopwatch under an object key and a later filter or endpoint reads it; it dies with the request. `HttpContext.Features` is an `IFeatureCollection` keyed by **interface type**; servers and middleware put capability objects there, and the friendly `HttpContext` properties are facades over them (`Items` itself is `IItemsFeature`, `TraceIdentifier` is `IHttpRequestIdentifierFeature`, `RequestAborted` is `IHttpRequestLifetimeFeature`). You reach for a feature when you need something the facade does not expose, such as raising `IHttpMaxRequestBodySizeFeature.MaxRequestBodySize` for one upload, or when middleware must replace a capability. `Features.Get<T>()` returns `null` if the server does not provide it, and `GetRequiredFeature<T>()` throws `InvalidOperationException`.
code
csharp · 13 linespublic static class TenantItems
{
private static readonly object Key = new();
public static void SetTenant(this HttpContext http, string tenant) =>
http.Items[Key] = tenant;
public static string? GetTenant(this HttpContext http) =>
http.Items.TryGetValue(Key, out var value) ? (string?)value : null;
}
// in middleware: context.SetTenant("acme");
// in a handler: var tenant = http.GetTenant();go deeper
Know that Items holds your own per-request values and that it is gone once the request ends.
Explain Features as the typed capability layer under HttpContext, name a few feature interfaces and show how Get<T>() and IsReadOnly behave.
Use features deliberately: per-endpoint limits set before the body is read, feature detection for host differences, and middleware that swaps a feature and restores it.
Decide what request data the platform exposes through typed Items helpers versus scoped services, so teams do not grow an untyped Items contract across libraries.
## Two dictionaries with different jobs Both members hang off the same `HttpContext` and both live exactly as long as one request, but they answer different questions: | | `HttpContext.Items` | `HttpContext.Features` | |---|---|---| | Type | `IDictionary<object, object?>` | `IFeatureCollection` | | Key | any object (a string or a private static object) | an interface `Type`, used through `Get<T>()` / `Set<T>()` | | Who writes it | your middleware, filters and endpoints | the server (Kestrel, IIS, HTTP.sys), the hosting layer and framework middleware | | What goes in | application data: a tenant id, a timer, a parsed header | capability objects: request and response plumbing, connection info, limits | | Missing entry | the indexer returns `null`; `TryGetValue` tells absent from null | `Get<T>()` returns `null`; `GetRequiredFeature<T>()` throws | ## Items: the application's per-request bag `Items` is the place to hand a value from an early stage of the pipeline to a later one in the **same** request. A tenant middleware in an invoicing API resolves the tenant from the host name once and stores it; an endpoint filter and the handler read it back. Because the key type is `object`, a library can use a `private static readonly object` key that nobody else can collide with, and expose typed extension methods instead of string lookups. The dictionary is a plain, non-thread-safe `Dictionary`, created lazily and dropped with the request, so it is neither shared between requests nor safe to write from parallel tasks. ## Features: the layer under HttpContext ASP.NET Core does not talk to the server through `HttpContext` directly. The server fills a feature collection with objects implementing small interfaces, and `DefaultHttpContext` is a set of facades over them: - `IHttpRequestFeature` — method, scheme, path base, path, query string, raw target, headers and body stream behind `HttpRequest`. - `IHttpResponseFeature` and `IHttpResponseBodyFeature` — status, headers, `HasStarted`, the body stream or pipe, `DisableBuffering()`. - `IHttpConnectionFeature` — connection id, remote and local IP address and port behind `HttpContext.Connection`. - `IHttpRequestLifetimeFeature` — `RequestAborted` and `Abort()`. - `IHttpRequestIdentifierFeature` — `TraceIdentifier`. - `IItemsFeature`, `IServiceProvidersFeature`, `IHttpAuthenticationFeature` — `Items`, `RequestServices` and `User`. - `IHttpMaxRequestBodySizeFeature`, `IHttpBodyControlFeature` — per-request limits and the `AllowSynchronousIO` switch. Framework middleware adds its own: routing sets the endpoint feature that `HttpContext.GetEndpoint()` reads, the exception handler publishes `IExceptionHandlerFeature`, the request-timeouts middleware publishes `IHttpRequestTimeoutFeature`. ## When to reach for a feature 1. **A per-request knob the facade does not expose.** Raising the body-size limit for one invoice-attachment upload is the classic case: ```csharp app.MapPost("/invoices/{id:int}/attachments", async (int id, HttpContext http) => { var limit = http.Features.Get<IHttpMaxRequestBodySizeFeature>(); if (limit is { IsReadOnly: false }) limit.MaxRequestBodySize = 50 * 1024 * 1024; // before reading the body await using var file = File.Create($"/data/{id}.pdf"); await http.Request.Body.CopyToAsync(file, http.RequestAborted); return Results.NoContent(); }); ``` Kestrel makes the feature read-only once the app has started consuming the body, and setting it then throws `InvalidOperationException`. 2. **Detecting what the host supports.** `Get<T>()` returning `null` tells you the server does not offer a capability, so the code can fall back instead of failing. 3. **Replacing or wrapping a capability** in middleware with `Features.Set<T>()`, for example swapping the response body feature to capture output, then restoring the original afterwards. ## Mistakes interviewers listen for - **Treating `Items` as cross-request storage.** It starts empty on every request; data that must reach the next request belongs in a cookie, `ISession` or a store. - **Assuming a missing `Items` key throws.** ASP.NET Core's items dictionary returns `null` from its indexer for an absent key, so a typo silently yields `null`; typed helpers with a single private key avoid that class of bug. - **Changing a feature too late.** Body-size limits, `AllowSynchronousIO` and response buffering decisions only make sense before the body is read or the response has started. - **Forgetting to restore a swapped feature.** Middleware that replaces `IHttpResponseBodyFeature` should put the original back in a `finally` block, or later middleware writes into the wrong stream. ## Rules of thumb - Put **your** data in `Items`; never invent a feature interface just to carry a tenant id. - Prefer the facade (`Request.Path`, `Connection.RemoteIpAddress`) when it exists; drop to `Features` only for what it lacks. - Treat both as **request-bound**: neither may be read after the response completes, and neither is safe for concurrent writes.
- In ASP.NET Core, what is the difference between Features.Get<T>() and GetRequiredFeature<T>()?`Get<T>()` returns `null` when no feature of that interface is registered, so the caller can fall back. `GetRequiredFeature<T>()` is an extension that throws `InvalidOperationException` ("Feature ... is not present") instead, which suits code that cannot work without the capability.
- With Kestrel, when can middleware still change IHttpMaxRequestBodySizeFeature.MaxRequestBodySize?Only before the app starts reading the request body and before an upgrade. After that `IsReadOnly` is `true` and the setter throws `InvalidOperationException`, so check `IsReadOnly` and set the limit early, in middleware or at the top of the handler.
- Items is shared between requests of the same user
- Features is just a second Items dictionary keyed by strings
- Features.Get<T>() throws when the server lacks the feature
- MaxRequestBodySize can be raised at any point while reading the body
- Items is a ConcurrentDictionary, so parallel tasks can write to it safely