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.
Do it: update the recently viewed list
The session keeps the ids of the products a visitor viewed last, newest first. Each time they open a product's page, the list changes. Write that change as a plain method; the session part (GetString, SetString and JSON) stays in the controller.
The method gets two values:
recent: the ids viewed so far, newest first, aList<int>([11, 5]).productId: the id of the product just viewed, anint(2).
The new list follows three rules:
- The product just viewed goes first.
- An id is in the list once: viewing a product again moves it to the front.
- The list keeps three ids at most: the oldest drops off the end.
For example, a visitor views products 11, 5, 11 and then 2:
| Viewed | The list after |
|---|---|
| (start) | [] |
| 11 | [11] |
| 5 | [5, 11] |
| 11 | [11, 5]: 11 moves to the front, once |
| 2 | [2, 11, 5] |
So RememberViewed(new List<int> { 11, 5 }, 2) returns [2, 11, 5].
Your job: write the method RememberViewed(List<int> recent, int productId) so it returns the new list, a List<int>.
- Put
productIdfirst. - If
productIdwas already in the list, it appears only once, at the front. - When there are more than three ids, keep the first three.
- An empty list gets only the new id:
[], then7, makes[7].
Practiced live on the lesson page: write the C# right there and check it.
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.