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




