Session State
Session state keeps small values on the server for one visitor between requests, such as recently viewed products, found through a session cookie. Turn it on, then SetString, GetString and SetInt32.
Journeyman · ASP.NET Core · C# · Updated
After this lesson you can
- Turn on session state, and store and read values with HttpContext.Session
Key takeaways
- Session state keeps small values on the server for one visitor between requests; the session cookie carries only the id.
- Turn it on with
AddDistributedMemoryCacheandAddSessionin the services, andapp.UseSession()after authorization. HttpContext.Session.SetStringandSetInt32store text and whole numbers by name;GetStringreturnsnullwhen there's none.- Store bigger values, such as a list of product ids, as JSON text with
JsonSerializer. - Keep anything that must survive in the database: sessions in memory are lost when the app restarts.
Each request is separate, so a variable in a controller is gone when the request ends. To remember something for one visitor across requests, such as the products they've just looked at, use session state.
How a session works
- On a visitor's first use of the session, ASP.NET Core makes an empty store on the server, and sends the browser a session cookie with its id.
- The browser sends the cookie back with every request.
- Each request finds that visitor's store by the id, and can read and write values in it.
- After a time with no requests (20 minutes, here), the store is thrown away.
The values stay on the server; the cookie only carries the id.
Turning it on
In Program.cs, register it with the services:
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
and add it to the pipeline, after authorization:
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
AddDistributedMemoryCache keeps sessions in the server's memory. HttpOnly stops scripts in the page from reading the cookie.
Storing and reading values
HttpContext.Session holds text and whole numbers, by name:
| Method | Does |
|---|---|
Session.SetString("Name", "value") |
Stores a piece of text |
Session.GetString("Name") |
Reads it, or null if there's none |
Session.SetInt32("Visits", 3) |
Stores an int |
Session.GetInt32("Visits") |
Reads it, as an int? |
Session.Remove("Name"), Session.Clear() |
Removes one value, or all of them |
For anything bigger, such as a list, store it as JSON text. NorthwindWeb remembers the last three products a visitor viewed:
private const string RecentlyViewedKey = "RecentlyViewed";
private List<int> RecentlyViewedIds()
{
string? json = HttpContext.Session.GetString(RecentlyViewedKey);
return json is null ? new List<int>() : JsonSerializer.Deserialize<List<int>>(json)!;
}
private void RememberViewed(int productId)
{
List<int> ids = RecentlyViewedIds();
ids.Remove(productId);
ids.Insert(0, productId);
HttpContext.Session.SetString(RecentlyViewedKey, JsonSerializer.Serialize(ids.Take(3).ToList()));
}
Details calls RememberViewed(id), and the product list reads the ids back to show Recently viewed links. View products 7, 3, 7 and 40, and the list shows Boston Crab Meat, Uncle Bob's Organic Dried Pears and Aniseed Syrup: newest first, no repeats, three at most. (JsonSerializer is in System.Text.Json; Take(3) keeps the first three items, as LINQ explains.)
What belongs in a session
| Good for the session | Not for the session |
|---|---|
| Small, short-lived values for one visitor: recently viewed items, a half-finished form's steps, a shopping cart before checkout | Anything that must survive: orders, accounts, settings. Those go in the database. |
| Who the user is: that's the sign-in cookie's job | |
| Large data: every session takes the server's memory |
Sessions in memory are lost when the app restarts, and aren't shared between servers. That's fine for "recently viewed"; for anything that matters, use the database.
Check yourself
1 question to try on the lesson page.
So what
A session is a small, temporary memory for each visitor: turn it on, store text or JSON by name, and read it back on the next request. Keep it small, and keep anything important in the database.
Key terms
- Session State