ASP.NET Core MVC Intermediate

Session state

Session state keeps per-user data on the server for the length of a visit, such as a shopping cart for a visitor who is not signed in. This lesson shows how to turn session on, read and write values, and what to watch out for when the app runs on several servers.

How session state works
  1. StartFirst requestThe server creates a session and a random session id
  2. Step 2Session cookie sentThe browser stores .AspNetCore.Session holding only the id
  3. Step 3Later requestsThe browser sends the cookie back with each request
  4. Step 4UseSession loads dataData for that id is loaded from the cache
  5. Step 5Your code reads and writesHttpContext.Session.GetString / SetString
  6. EndIdle timeoutAfter 20 minutes without requests (by default) the data is removed

The idea in plain words

With session, the browser only holds an id in a cookie, and the actual data stays on the server in a cache. That means you can store more than a cookie allows, and users cannot read or change the values directly.

Session is not permanent storage. Data disappears after the idle timeout, and with the default in-memory cache it is also lost when the app restarts. If your app runs on more than one server, use a distributed cache such as Redis or SQL Server so every server sees the same session.

Example: turn session on

Register a cache and session services, then add the middleware after routing and before the endpoints.

C#
builder.Services.AddDistributedMemoryCache(); // swap for Redis in production farms
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(20);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

var app = builder.Build();
app.UseRouting();
app.UseSession();
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

Example: use it in a controller

Session stores strings, integers and byte arrays. For objects, serialize to JSON.

C#
public IActionResult AddToCart(int productId)
{
    var json = HttpContext.Session.GetString("Cart");
    var cart = json is null ? new List<int>() : JsonSerializer.Deserialize<List<int>>(json)!;
    cart.Add(productId);
    HttpContext.Session.SetString("Cart", JsonSerializer.Serialize(cart));
    HttpContext.Session.SetInt32("CartCount", cart.Count);
    return RedirectToAction("Index", "Cart");
}

Common mistakes

  • Calling UseSession after the endpoints, so HttpContext.Session throws.
  • Using the in-memory cache behind a load balancer, so users randomly lose their cart.
  • Storing large object graphs in session; every request loads them.
  • Using session for data that must not be lost, such as orders. Save that in the database.

Interview question

How does session state work in ASP.NET Core, and what are its limitations?

ASP.NET Core issues a cookie containing a session id; the session data itself is stored server-side in an IDistributedCache implementation. The session middleware loads the data for that id on each request and saves changes at the end. Limitations: data expires after an idle timeout, is lost on restart with the in-memory cache, needs a shared distributed cache across multiple servers, only stores byte arrays (strings and ints via helpers), and should not hold large or critical data.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.