liveBook · Manning

Session

As explained in Pro ASP.NET Core 7, Tenth Edition

Session state is client-specific data stored on the server for access across multiple requests within a session.

A session keeps client-specific data available across related HTTP requests. ASP.NET Core sends the browser a session cookie that identifies those requests; the application data stays on the server. This avoids putting editable application state in a client-side cookie. section 16.3

Set up sessions in Program.cs:

  • Register a cache with AddDistributedMemoryCache(), then register session services with AddSession(). section 16.3.1
  • Call UseSession() before middleware or endpoints that access HttpContext.Session. The session data is not available to components earlier in the pipeline. section 16.3.2
  • Configure SessionOptions when needed. IdleTimeout can expire an inactive session; Cookie.IsEssential can prevent cookie-consent settings from silently stopping sessions. section 16.3.1
Listing 16.7 Configuring sessions in the Program.cs file in the Platform folder
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDistributedMemoryCache();

builder.Services.AddSession(opts => {
    opts.IdleTimeout = TimeSpan.FromMinutes(30);
    opts.Cookie.IsEssential = true;
});

var app = builder.Build();

app.UseSession();

app.MapFallback(async context =>
    await context.Response.WriteAsync("Hello World!"));
        
app.Run();

This Program.cs setup uses an in-memory cache, a 30-minute idle timeout, an essential session cookie, and UseSession(). section 16.3.1

Read and write keyed values through HttpContext.Session. ISession provides methods such as GetInt32, SetInt32, GetString, SetString, Remove, and Clear. Read, update, and store data before sending the response. CommitAsync is optional, but makes a cache-storage failure throw an exception instead of going unreported. section 16.3.2

Count requests in one session

At /session, read GetInt32("counter1") ?? 0, increment it, store it with SetInt32, commit, and write the result. The middleware handles the cookie and loads the associated data; the endpoint works with HttpContext.Session. section 16.3.2

For a shopping cart, serialize the Cart object to JSON and store the resulting string in the session; deserialize it on a later request. In-memory storage is simple, but loses data when the application stops or restarts and serves only one runtime instance. SQL Server and Redis caches are alternatives when that constraint matters. section 8.2.5 section 16.3.1

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Works through service registration, middleware placement, storage choices, options, keyed access, and commits without detailing cache internals.
Examples
Uses a request counter endpoint and a JSON-serialized shopping cart to demonstrate persistence across requests.
What it assumes
Assumes familiarity with Program.cs and HTTP requests while showing the service and middleware setup needed for sessions.
What you can do after
Operate/configure it to retain per-client values across requests and detect cache-write failures with CommitAsync.
How it connects
Connects sessions to cookies, middleware, caching, JSON serialization, Razor Pages, and shopping carts.

Also explained in

Compare how 5 books explain session →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.