How is TempData stored, and what are its providers?

ASP.NET MVC Views & Razor Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

TempData survives exactly one redirect. In ASP.NET Core the default provider is a cookie (encrypted); you can switch to the session provider. Values are serialized, so only simple types (string, int, and simple collections) round-trip reliably — not complex objects.

TempData is designed to carry a value across a single redirect. In ASP.NET Core it's backed by an encrypted cookie by default, or you can use the session provider. Because it serializes, I keep it to strings and simple values, not whole objects. Reading a key consumes it, so if I need it twice I use Peek or Keep. The classic use is the flash message: I do a POST, save the record, put “Order created” in TempData, redirect to the details page, and show it there.

  • Reading a key marks it for deletion; TempData.Peek(key) reads without consuming; TempData.Keep(key) retains it for another request.
  • Cookie provider — no server state, but adds to every response size and is limited to ~4KB.
  • Session provider — needs AddSession() and a distributed cache in a multi-instance app.
  • Main use: a “Saved successfully” flash message after the POST-redirect-GET pattern.