skip to content

ISession & TempData

AddSession and UseSession give a cookie-keyed ISession stored in IDistributedCache, and TempData carries values across one redirect. Interviewers probe IdleTimeout, LoadAsync and stateless APIs.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

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%

answer

  1. a store, a service, a middleware
  2. IDistributedCache behind the session
  3. AddSession plus app.UseSession()
  4. SetString / GetString, SetInt32 / GetInt32
  5. ISession holds byte[] only

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.

solid answer

~30 s

Three 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 lines
csharp
var 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

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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
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 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

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