In ASP.NET Core 10, what must Program.cs register to use HttpContext.Session, and how does a handler store and read a value?
answer
- a store, a service, a middleware
- IDistributedCache behind the session
- AddSession plus app.UseSession()
- SetString / GetString, SetInt32 / GetInt32
- ISession holds byte[] only
basics
~20 sSession 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.
solid answer
~30 sThree registrations. An `IDistributedCache` is the store: `AddDistributedMemoryCache()` for a single instance, a shared cache in a farm. `builder.Services.AddSession(o => ...)` registers `DistributedSessionStore`, adds Data Protection and binds `SessionOptions`. `app.UseSession()` runs before the endpoints that touch session: it reads the `.AspNetCore.Session` cookie, attaches an `ISession` to the request and commits it when the request ends. In a handler, `HttpContext.Session.SetString("step", "income")` writes and `GetString("step")` returns the string or `null`; `SetInt32` / `GetInt32` (an `int?`) do the same for integers. `ISession` itself stores `byte[]` through `Set` and `TryGetValue`, so a wizard's answers object goes in as JSON. Without `UseSession`, reading `HttpContext.Session` throws `InvalidOperationException`.
code
csharp · 17 linesvar builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddDistributedMemoryCache(); // the IDistributedCache the session lives in
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.IsEssential = true;
});
var app = builder.Build();
app.UseRouting();
app.UseSession(); // before the endpoints that read HttpContext.Session
app.MapRazorPages();
app.Run();go deeper
Recall the three registrations, a distributed cache, AddSession and UseSession, then show SetString and GetString on HttpContext.Session and say that objects must be serialized first.
Explain what the middleware does per request: read and unprotect the cookie, attach ISession, commit at the end. Mention that GetInt32 returns int? and that a missing UseSession throws InvalidOperationException.
Point out that MVC and Razor Pages register an in-memory IDistributedCache implicitly, so session silently becomes per-instance, and that session is not supported under Native AOT.
Frame session as a deliberate choice: what state truly belongs to one browser, what belongs in the database, and whether a stateless API should carry it in the request instead.
## What session state is in ASP.NET Core **Session state** keeps a small amount of per-browser data on the server between requests. ASP.NET Core implements it with three cooperating parts: a cookie that carries an opaque **session key**, a server-side record stored in an `IDistributedCache` under that key, and the `ISession` object that a handler reads and writes during one request. Nothing is enabled by default; an app opts in through `Program.cs`. ## The three registrations 1. **A store.** `builder.Services.AddDistributedMemoryCache()` registers `MemoryDistributedCache`, an `IDistributedCache` that lives in the process. A farm needs a shared implementation instead (Redis, SQL Server and others belong to the distributed-caching topic). 2. **The session services.** `builder.Services.AddSession(options => { ... })` registers `DistributedSessionStore` as the `ISessionStore`, calls `AddDataProtection()` (the cookie value is protected) and lets you configure `SessionOptions`. 3. **The middleware.** `app.UseSession()` adds `SessionMiddleware`. For each request it reads the cookie, unprotects the key (or mints a new one), creates a `DistributedSession`, exposes it as `ISessionFeature`, runs the rest of the pipeline and finally calls `CommitAsync`. One trap hides in step 1. `AddControllersWithViews()` and `AddRazorPages()` already call `AddDistributedMemoryCache()` for the cache tag helper, so an MVC or Razor Pages app "works" without registering a store and silently keeps sessions in process memory. A Minimal API app has no such registration, and `AddSession` alone fails at startup: the container reports that it cannot resolve `IDistributedCache` while activating `DistributedSessionStore`. ## Reading and writing values `ISession` is deliberately small: `Set(string, byte[])`, `TryGetValue(string, out byte[]?)`, `Remove`, `Clear`, `Keys`, `Id`, `IsAvailable`, `LoadAsync` and `CommitAsync`. The extension methods in `SessionExtensions` add the everyday shapes: | Method | Stores | Returns when the key is missing | |---|---|---| | `SetString` / `GetString` | UTF-8 bytes of a string | `null` | | `SetInt32` / `GetInt32` | four big-endian bytes | `null` (an `int?`) | | `Get` | raw `byte[]` | `null` | Anything richer, such as the income and property answers of a mortgage pre-approval wizard, must be **serialized** by your code, typically with `JsonSerializer.Serialize` on the way in and `JsonSerializer.Deserialize<T>` on the way out. The store keeps bytes, not live objects, even when it is the in-memory cache. ## Where session is available - `HttpContext.Session` works in Minimal API handlers, controllers, Razor Pages and middleware alike, because it is a property of `HttpContext`. - Reading it on a request that did not pass through `UseSession` throws `InvalidOperationException`: *Session has not been configured for this application or request.* - Session state does not support trimming or Native AOT; `AddSession` carries `[RequiresUnreferencedCode]`. - A JSON API consumed by scripts or mobile clients usually has no use for it: the caller would have to keep the session cookie, and the state lives in one server's store. ## What the first write does - A new visitor gets no cookie until code actually calls `Set` (directly or through `SetString`); the middleware appends `.AspNetCore.Session` from a `Response.OnStarting` callback. - If a brand-new session is written after the response has started, `Set` throws *The session cannot be established after the response has started.* - At the end of the request the middleware calls `CommitAsync`, which writes the whole record if anything changed, or refreshes the idle timer if nothing did. Together these explain the usual shape of an interview answer: register a store, add the services, add the middleware, then treat `ISession` as a small byte-oriented dictionary that you serialize into.
- Why does an ASP.NET Core Razor Pages app run session without AddDistributedMemoryCache, while a Minimal API app fails at startup?`AddRazorPages()` and `AddControllersWithViews()` register the cache tag helper services, which call `AddDistributedMemoryCache()`. `DistributedSessionStore` therefore finds an in-memory `IDistributedCache`. A Minimal API app registers none, so activating `DistributedSessionStore` fails at startup because `IDistributedCache` cannot be resolved. The Razor Pages case is the more dangerous one: it hides that session data lives in one process.
- Would you use ASP.NET Core session for a JSON API that a mobile app calls?Usually not. Session depends on the client returning the `.AspNetCore.Session` cookie, keeps state in a server-side store that must be shared across instances, and is not supported under Native AOT. An API normally carries what it needs in the request itself, such as a bearer token and explicit identifiers, and keeps durable state in its database.
- AddMemoryCache provides the store that AddSession needs
- AddSession alone turns on session; UseSession is optional
- ISession can store any object directly, without serialization
- GetString throws KeyNotFoundException when the key is missing
- Session works only in MVC controllers, not in Minimal API handlers