In ASP.NET Core 10 MVC, how do the cookie and session TempData providers differ, and when would you switch to AddSessionStateTempDataProvider?
answer
- where the bytes live between requests
- CookieTempDataProvider is the default
- Data Protection, base64url, chunked cookie
- AddSessionStateTempDataProvider needs UseSession
- same serializer, same type limits
basics
~20 sCookieTempDataProvider, 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.
solid answer
~40 sMVC registers `CookieTempDataProvider` by default. It serializes the dictionary, protects it with Data Protection, base64url-encodes it and writes the `.AspNetCore.Mvc.CookieTempDataProvider` cookie (chunked when large, deleted when TempData is empty). No server state is involved, so it works across instances as long as they share a Data Protection key ring; an unreadable cookie is logged as a warning and deleted, and TempData is simply empty. `builder.Services.AddControllersWithViews().AddSessionStateTempDataProvider()` swaps in `SessionStateTempDataProvider`, which stores the same serialized bytes under one key in `ISession` and removes them when loaded. It needs `AddSession`, `UseSession` and a shared `IDistributedCache` in a farm, and `HttpContext.Session` throws without them. Switch when the app already uses session or TempData grows beyond a few hundred bytes.
code
csharp · 11 linesbuilder.Services.AddDistributedMemoryCache(); // replace with a shared cache in a farm
builder.Services.AddSession();
builder.Services.AddControllersWithViews()
.AddSessionStateTempDataProvider(); // TempData now lives in ISession
var app = builder.Build();
app.UseRouting();
app.UseSession(); // required, or HttpContext.Session throws
app.MapDefaultControllerRoute();
app.Run();go deeper
Know that TempData is stored in a cookie by default and that a session-based alternative exists.
Describe the cookie pipeline, serialize, protect, base64url-encode and chunk, and list what AddSessionStateTempDataProvider needs in Program.cs: AddSession, UseSession and a distributed cache.
Explain the farm failure modes: unshared Data Protection keys silently empty the cookie provider, and the session provider inherits session's store and middleware requirements.
Pick one home for transient UI state across the app and keep business-critical data out of TempData entirely.
## Same dictionary, two homes `TempData` behaves the same whichever provider stores it: reads mark keys for deletion, `Peek` and `Keep` retain them, and the same `TempDataSerializer` limits values to simple types. What an `ITempDataProvider` decides is **where the serialized dictionary waits between requests**. MVC's view features register `CookieTempDataProvider` with `TryAddSingleton`; `AddSessionStateTempDataProvider()` and `AddCookieTempDataProvider()` replace that registration explicitly. | Aspect | `CookieTempDataProvider` (default) | `SessionStateTempDataProvider` | |---|---|---| | Enabled by | nothing; it is the default | `AddSessionStateTempDataProvider()` on `IMvcBuilder` | | Where data lives | the `.AspNetCore.Mvc.CookieTempDataProvider` cookie | one entry inside `ISession` | | Protection | Data Protection, then base64url | the session store; the session cookie is protected | | Prerequisites | Data Protection keys shared across instances | `AddSession`, `UseSession`, an `IDistributedCache` | | Cost per request | cookie bytes travel until consumed | a session load and commit | | Failure mode | unreadable cookie: Warning log, cookie deleted, TempData empty | no session middleware: `InvalidOperationException` | | Options | `CookieTempDataProviderOptions.Cookie` | `SessionOptions` | ## How the cookie provider works 1. On save, the dictionary is serialized to JSON bytes, protected by an `IDataProtector` created for the purpose `Microsoft.AspNetCore.Mvc.CookieTempDataProviderToken.v1`, and encoded with base64url. 2. The value is written through the chunking cookie manager, which splits it into several cookies when it exceeds the chunk size of 4,050 characters. Browsers cap cookie size and count, so a large TempData can still be rejected. 3. When the dictionary is empty, the cookie is deleted. 4. On load, a cookie that cannot be decoded or unprotected, typically because the instance does not have the key that protected it, is **not** an error page: the provider logs a `TempDataCookieLoadFailure` warning, deletes the cookie, and TempData starts empty. The cookie defaults are `HttpOnly = true`, `SameSite = Lax`, `IsEssential = false` and `SecurePolicy = None`, configured through `AddCookieTempDataProvider(o => o.Cookie...)` or `services.Configure<CookieTempDataProviderOptions>`. Because the cookie is not essential, a consent policy that requires consent suppresses it. ## How the session provider works - Saving calls `HttpContext.Session.Set` with the serialized bytes under a single internal key; an empty dictionary removes that key. - Loading reads the key and **removes it from the session immediately**, so no other request picks the same bytes up. - Accessing `HttpContext.Session` throws *Session has not been configured for this application or request* when `UseSession` is missing, so TempData use fails loudly rather than silently. - In a farm it inherits session's requirements: a shared `IDistributedCache` and, for the session cookie, a shared key ring. ## Choosing - **Stay with cookies** for short confirmation messages, a few hundred bytes at most, in apps that do not otherwise use session. There is no server state to share and nothing to configure beyond Data Protection. - **Switch to session** when the app already depends on session, or when TempData carries more than a short message, so that the data stops riding on every request until it is read. - **Avoid both** for anything a business flow cannot lose. TempData is best-effort by design: the cookie provider throws away what it cannot read, and session state expires after its idle window. In a mortgage pre-approval site that already keeps its wizard steps in session, moving the one-time "saved" message into the session provider removes one cookie and keeps all transient state in a single place.
- With the default ASP.NET Core TempData provider, why might a 'saved' message vanish only in production behind a load balancer?The cookie is protected with Data Protection. If the instances do not share a key ring and application name, an instance that did not write the cookie cannot unprotect it. `CookieTempDataProvider` then logs a warning, deletes the cookie and returns an empty dictionary, so the banner disappears without an error. Sharing the key ring fixes it.
- Does switching to SessionStateTempDataProvider lift the TempData type restrictions?No. Both providers call the same `TempDataSerializer`, which accepts strings, integers, booleans, `DateTime`, `Guid`, enums and a few string or integer collections. A custom object still throws `InvalidOperationException` when TempData is saved; serialize it yourself or store an identifier.
- TempData uses session state by default in ASP.NET Core MVC
- The cookie TempData provider stores values as readable plain text
- The cookie provider needs sticky sessions to work behind a load balancer
- AddSessionStateTempDataProvider works without UseSession by falling back to cookies
- The session provider lets TempData hold arbitrary objects