Sessions

suggest change

HTTP is stateless: every request stands alone. A session lets a web app remember data about one visitor across requests, for example a shopping cart, a multi-step form or a preference.

In ASP.NET Core a session works like this:

The cookie only identifies the session. The data never travels to the client. For cookies in general, see Cookies.

Every example below is a complete program. It starts a small ASP.NET Core app (dotnet new web), calls it with HttpClient the way a browser would, prints the results and stops. All were run with .NET 10.


1. Enabling sessions

Sessions need three things: a cache to store the data, the session services and the session middleware:

using System.Net;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();

builder.Services.AddDistributedMemoryCache();   // where session data is stored
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(20);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

var app = builder.Build();
app.UseSession();                                // must come before endpoints that use it

app.MapGet("/visit", (HttpContext ctx) =>
{
    int count = (ctx.Session.GetInt32("visits") ?? 0) + 1;
    ctx.Session.SetInt32("visits", count);
    return $"visit #{count} (session {ctx.Session.Id[..8]})";
});

app.MapGet("/whoami", (HttpContext ctx) =>
{
    ctx.Session.SetString("name", ctx.Request.Query["name"].ToString());
    return "name saved";
});

app.MapGet("/hello", (HttpContext ctx) =>
    $"hello {ctx.Session.GetString("name") ?? "stranger"}");

const string baseUrl = "http://localhost:5301";
app.Urls.Add(baseUrl);
await app.StartAsync();

// Two "browsers", each with its own cookie jar
HttpClient NewBrowser() =>
    new(new HttpClientHandler { CookieContainer = new CookieContainer() })
    { BaseAddress = new Uri(baseUrl) };

using var alice = NewBrowser();
using var bob = NewBrowser();

Console.WriteLine("alice: " + await alice.GetStringAsync("/visit"));
Console.WriteLine("alice: " + await alice.GetStringAsync("/visit"));
Console.WriteLine("bob:   " + await bob.GetStringAsync("/visit"));
Console.WriteLine("alice: " + await alice.GetStringAsync("/visit"));

await alice.GetStringAsync("/whoami?name=Alice");
Console.WriteLine("alice: " + await alice.GetStringAsync("/hello"));
Console.WriteLine("bob:   " + await bob.GetStringAsync("/hello"));

// A client without cookies gets a brand new session every time
using var noCookies = new HttpClient(new HttpClientHandler { UseCookies = false })
    { BaseAddress = new Uri(baseUrl) };
var resp = await noCookies.GetAsync("/visit");
Console.WriteLine("raw:   " + await resp.Content.ReadAsStringAsync());
Console.WriteLine("Set-Cookie: " + string.Join(" | ", resp.Headers.GetValues("Set-Cookie")));
Console.WriteLine("raw:   " + await noCookies.GetStringAsync("/visit"));

await app.StopAsync();

Output:

alice: visit #1 (session 72bace9c)
alice: visit #2 (session 72bace9c)
bob:   visit #1 (session b8b57ccd)
alice: visit #3 (session 72bace9c)
alice: hello Alice
bob:   hello stranger
raw:   visit #1 (session 587fd111)
Set-Cookie: .AspNetCore.Session=CfDJ8D0l7PKdItBEpIkmR7I84mmItGYfEDFVo4DaQVSp5RPAn67Cjj%2BuoQwR1SxKe5Jeh3h%2FDscXVGu2HhlYeE1QvI160AiglLzSpZGzumF0hDww6WtW304cj%2FYIwF7zWhwG%2F0fWthk2tfFenl0Ksq8HiAKAaUtXHLq%2BBRKxYqE%2F3%2FYI; path=/; samesite=lax; httponly
raw:   visit #1 (session 31a656c3)

Notes:


2. The ISession API

ISession stores values as byte[]. The core methods are:

Member What it does
Set(key, byte[]) / TryGetValue(key, out byte[]) Store / read raw bytes
SetString / GetString Extension methods, UTF-8 strings
SetInt32 / GetInt32 Extension methods, 32-bit integers
Remove(key) / Clear() Delete one key / all keys
Keys Names of all stored keys
Id Unique id of the session (not the cookie value)
IsAvailable true if the session was loaded successfully
LoadAsync() / CommitAsync() Load from / save to the store explicitly

GetString and GetInt32 return null when the key doesn't exist, which is why the examples use ?? defaultValue.


3. Storing objects as JSON

There is no built-in way to store an object, but two extension methods built on System.Text.Json do the job:

using System.Net;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();

var app = builder.Build();
app.UseSession();

app.MapPost("/cart/add", (HttpContext ctx, string sku, int qty) =>
{
    var cart = ctx.Session.Get<Cart>("cart") ?? new Cart();
    var line = cart.Lines.FirstOrDefault(l => l.Sku == sku);
    if (line is null) cart.Lines.Add(new CartLine(sku, qty));
    else cart.Lines[cart.Lines.IndexOf(line)] = line with { Qty = line.Qty + qty };

    ctx.Session.Set("cart", cart);   // must store it again: Get returned a copy
    return $"{cart.Lines.Sum(l => l.Qty)} item(s) in cart";
});

app.MapGet("/cart", (HttpContext ctx) =>
    ctx.Session.Get<Cart>("cart") ?? new Cart());   // serialized to JSON response

app.MapGet("/cart/raw", (HttpContext ctx) =>
    ctx.Session.TryGetValue("cart", out byte[]? bytes)
        ? $"{bytes.Length} bytes: {System.Text.Encoding.UTF8.GetString(bytes)}"
        : "empty");

const string baseUrl = "http://localhost:5302";
app.Urls.Add(baseUrl);
await app.StartAsync();

using var client = new HttpClient(new HttpClientHandler { CookieContainer = new CookieContainer() })
    { BaseAddress = new Uri(baseUrl) };

async Task Post(string url) =>
    Console.WriteLine(await (await client.PostAsync(url, null)).Content.ReadAsStringAsync());

await Post("/cart/add?sku=BOOK-1&qty=1");
await Post("/cart/add?sku=PEN-7&qty=3");
await Post("/cart/add?sku=BOOK-1&qty=2");
Console.WriteLine(await client.GetStringAsync("/cart"));
Console.WriteLine(await client.GetStringAsync("/cart/raw"));

await app.StopAsync();

record CartLine(string Sku, int Qty);
class Cart { public List<CartLine> Lines { get; set; } = []; }

static class SessionJsonExtensions
{
    public static void Set<T>(this ISession session, string key, T value) =>
        session.Set(key, JsonSerializer.SerializeToUtf8Bytes(value));

    public static T? Get<T>(this ISession session, string key) =>
        session.TryGetValue(key, out byte[]? bytes)
            ? JsonSerializer.Deserialize<T>(bytes)
            : default;
}

Output:

1 item(s) in cart
4 item(s) in cart
6 item(s) in cart
{"lines":[{"sku":"BOOK-1","qty":3},{"sku":"PEN-7","qty":3}]}
60 bytes: {"Lines":[{"Sku":"BOOK-1","Qty":3},{"Sku":"PEN-7","Qty":3}]}

Two things to remember:

(The /cart response uses camelCase because minimal APIs serialize with web defaults. The raw bytes use JsonSerializer's default PascalCase. Both work as long as Set and Get use the same options.)


4. Session lifetime: creating, removing, clearing and expiring

This example watches the session id, the stored keys and the browser's cookie jar. IdleTimeout is set to 2 seconds so expiration can be shown quickly:

using System.Net;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(o => o.IdleTimeout = TimeSpan.FromSeconds(2)); // tiny, for the demo

var app = builder.Build();
app.UseSession();

app.MapGet("/read", (HttpContext ctx) =>
    $"id={ctx.Session.Id[..6]} keys=[{string.Join(",", ctx.Session.Keys)}]");

app.MapGet("/login", (HttpContext ctx) =>
{
    ctx.Session.SetString("user", "alice");
    ctx.Session.SetString("theme", "dark");
    ctx.Session.SetInt32("cartItems", 2);
    return "logged in";
});

app.MapGet("/remove-theme", (HttpContext ctx) => { ctx.Session.Remove("theme"); return "removed"; });
app.MapGet("/logout", (HttpContext ctx) => { ctx.Session.Clear(); return "cleared"; });

const string baseUrl = "http://localhost:5303";
app.Urls.Add(baseUrl);
await app.StartAsync();

var jar = new CookieContainer();
using var client = new HttpClient(new HttpClientHandler { CookieContainer = jar })
    { BaseAddress = new Uri(baseUrl) };

async Task Call(string url)
{
    using var resp = await client.GetAsync(url);
    string body = await resp.Content.ReadAsStringAsync();
    Console.WriteLine($"{url,-14} -> {body,-38} cookies in jar: {jar.Count}");
}

await Call("/read");          // reading an empty session doesn't create a cookie
await Call("/login");
await Call("/read");
await Call("/remove-theme");
await Call("/read");
await Call("/logout");
await Call("/read");

await Call("/login");
await Task.Delay(TimeSpan.FromSeconds(3));  // idle longer than IdleTimeout
await Call("/read");

await app.StopAsync();

Output:

/read          -> id=afc819 keys=[]                      cookies in jar: 0
/login         -> logged in                              cookies in jar: 1
/read          -> id=dc9ff6 keys=[user,theme,cartItems]  cookies in jar: 1
/remove-theme  -> removed                                cookies in jar: 1
/read          -> id=dc9ff6 keys=[user,cartItems]        cookies in jar: 1
/logout        -> cleared                                cookies in jar: 1
/read          -> id=dc9ff6 keys=[]                      cookies in jar: 1
/login         -> logged in                              cookies in jar: 1
/read          -> id=6eb369 keys=[]                      cookies in jar: 1

What the output shows:


5. A typed session wrapper and async loading

Scattering string keys like "prefs.lang" all over the code leads to typos. A small service that wraps ISession keeps keys, defaults and validation in one place:

using System.Net;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<UserPrefs>();

var app = builder.Build();

// Only /app/* gets session support; /health stays session-free
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/app"), branch => branch.UseSession());

app.MapPost("/app/prefs", async (UserPrefs prefs, string lang, int pageSize) =>
{
    await prefs.LoadAsync();
    prefs.Language = lang;
    prefs.PageSize = pageSize;
    return "saved";
});

app.MapGet("/app/prefs", async (UserPrefs prefs) =>
{
    await prefs.LoadAsync();
    return $"lang={prefs.Language} pageSize={prefs.PageSize}";
});

app.MapGet("/health", (HttpContext ctx) =>
{
    try { return $"session keys: {ctx.Session.Keys.Count()}"; }
    catch (InvalidOperationException ex) { return $"error: {ex.Message}"; }
});

const string baseUrl = "http://localhost:5304";
app.Urls.Add(baseUrl);
await app.StartAsync();

using var client = new HttpClient(new HttpClientHandler { CookieContainer = new CookieContainer() })
    { BaseAddress = new Uri(baseUrl) };

Console.WriteLine(await client.GetStringAsync("/app/prefs"));
var r = await client.PostAsync("/app/prefs?lang=pl&pageSize=50", null);
Console.WriteLine(await r.Content.ReadAsStringAsync());
Console.WriteLine(await client.GetStringAsync("/app/prefs"));
Console.WriteLine(await client.GetStringAsync("/health"));

await app.StopAsync();

// A typed facade over ISession: keys and conversions live in one place
class UserPrefs(IHttpContextAccessor accessor)
{
    ISession Session => accessor.HttpContext?.Session
        ?? throw new InvalidOperationException("No active HTTP request");

    // Loads the session from the store asynchronously instead of blocking on first access
    public Task LoadAsync() => Session.LoadAsync();

    public string Language
    {
        get => Session.GetString("prefs.lang") ?? "en";
        set => Session.SetString("prefs.lang", value);
    }

    public int PageSize
    {
        get => Session.GetInt32("prefs.pageSize") ?? 20;
        set => Session.SetInt32("prefs.pageSize", Math.Clamp(value, 10, 100));
    }
}

Output:

lang=en pageSize=20
saved
lang=pl pageSize=50
error: Session has not been configured for this application or request.

Notes:


6. Concurrent requests: last write wins

ASP.NET Core sessions are not locked (unlike classic ASP.NET). Each request loads its own copy of the data and the last request to finish overwrites the others:

using System.Net;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();

var app = builder.Build();
app.UseSession();

app.MapGet("/inc", async (HttpContext ctx) =>
{
    int n = ctx.Session.GetInt32("n") ?? 0;
    await Task.Delay(50);                  // simulate some work
    ctx.Session.SetInt32("n", n + 1);
    return n + 1;
});
app.MapGet("/n", (HttpContext ctx) => ctx.Session.GetInt32("n") ?? 0);

const string baseUrl = "http://localhost:5305";
app.Urls.Add(baseUrl);
await app.StartAsync();

using var client = new HttpClient(new HttpClientHandler { CookieContainer = new CookieContainer() })
    { BaseAddress = new Uri(baseUrl) };

await client.GetStringAsync("/inc");               // create the session first

// 10 sequential requests
for (int i = 0; i < 10; i++) await client.GetStringAsync("/inc");
Console.WriteLine($"after 10 sequential: {await client.GetStringAsync("/n")}");

// 10 concurrent requests from the same "browser"
await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => client.GetStringAsync("/inc")));
Console.WriteLine($"after 10 concurrent: {await client.GetStringAsync("/n")}");

await app.StopAsync();

Output:

after 10 sequential: 11
after 10 concurrent: 12

The 10 concurrent requests all read 11, each wrote 12, and 9 increments were lost. Browsers send parallel requests all the time (AJAX calls, several tabs), so don't use the session for counters, stock levels, balances or anything else that must be updated atomically. Keep that in a database with proper transactions.


7. Sessions and sign-in

A session is not authentication. Anyone who has the session cookie can use the session, and the session middleware doesn't know who the user is. Use the authentication cookie (see Cookies and ASP.NET Identity) for identity, and the session only for UI state:

using System.Net;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
builder.Services.AddAuthorization();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();

app.MapGet("/browse", (HttpContext ctx) =>
{
    ctx.Session.SetString("lastPage", "/products/42");   // anonymous session data
    return "browsing";
});

app.MapPost("/login", async (HttpContext ctx, string user) =>
{
    ctx.Session.Clear();                                  // drop anything set before login
    var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, user)],
        CookieAuthenticationDefaults.AuthenticationScheme);
    await ctx.SignInAsync(new ClaimsPrincipal(identity)); // identity goes in the auth cookie
    ctx.Session.SetString("wizardStep", "1");             // session holds only UI state
    return $"signed in as {user}";
});

app.MapGet("/status", (HttpContext ctx) =>
    $"user={ctx.User.Identity?.Name ?? "-"} " +
    $"keys=[{string.Join(",", ctx.Session.Keys)}]");

app.MapPost("/logout", async (HttpContext ctx) =>
{
    ctx.Session.Clear();
    ctx.Response.Cookies.Delete(".AspNetCore.Session");   // forget the session id too
    await ctx.SignOutAsync();
    return "signed out";
});

const string baseUrl = "http://localhost:5306";
app.Urls.Add(baseUrl);
await app.StartAsync();

var jar = new CookieContainer();
using var client = new HttpClient(new HttpClientHandler { CookieContainer = jar })
    { BaseAddress = new Uri(baseUrl) };
async Task<string> Post(string url) => await (await client.PostAsync(url, null)).Content.ReadAsStringAsync();

Console.WriteLine(await client.GetStringAsync("/browse"));
Console.WriteLine(await client.GetStringAsync("/status"));
Console.WriteLine(await Post("/login?user=alice"));
Console.WriteLine(await client.GetStringAsync("/status"));
Console.WriteLine("cookies: " + string.Join(", ", jar.GetAllCookies().Select(c => c.Name)));
Console.WriteLine(await Post("/logout"));
Console.WriteLine(await client.GetStringAsync("/status"));
Console.WriteLine("cookies: " + string.Join(", ", jar.GetAllCookies().Select(c => c.Name)));

await app.StopAsync();

Output:

browsing
user=- keys=[lastPage]
signed in as alice
user=alice keys=[wizardStep]
cookies: .AspNetCore.Session, .AspNetCore.Cookies
signed out
user=- keys=[]
cookies: 

8. Production: Redis and multiple servers

AddDistributedMemoryCache keeps data in one process. With several servers behind a load balancer, or when sessions must survive a restart, store sessions in a shared distributed cache. The session code doesn't change, only the registration.

With Redis (dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis and Microsoft.AspNetCore.DataProtection.StackExchangeRedis):

using Microsoft.AspNetCore.DataProtection;
using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);

string redis = builder.Configuration.GetConnectionString("Redis") ?? "localhost:6379";
var mux = ConnectionMultiplexer.Connect(redis);

// 1. Session data lives in Redis instead of server memory
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.ConnectionMultiplexerFactory = () => Task.FromResult<IConnectionMultiplexer>(mux);
    options.InstanceName = "myapp:";            // key prefix, e.g. "myapp:<session key>"
});

// 2. All servers must decrypt each other's session cookies
builder.Services.AddDataProtection()
    .SetApplicationName("myapp")
    .PersistKeysToStackExchangeRedis(mux, "myapp:dataprotection-keys");

builder.Services.AddSession(options =>
{
    options.Cookie.Name = "__Host-sid";
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.IsEssential = true;
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.IOTimeout = TimeSpan.FromSeconds(5); // max time to wait for the store
});

var app = builder.Build();
app.UseHttpsRedirection();
app.UseSession();

app.MapGet("/", (HttpContext ctx) =>
{
    int n = (ctx.Session.GetInt32("n") ?? 0) + 1;
    ctx.Session.SetInt32("n", n);
    return $"request {n} served by {Environment.MachineName}";
});

app.Run();

Things that matter in production:


9. Session options reference

Option Default Meaning
IdleTimeout 20 minutes How long session data survives without requests (sliding)
IOTimeout 1 minute Max time to load from / commit to the store
Cookie.Name .AspNetCore.Session Name of the session cookie
Cookie.HttpOnly true Hide the cookie from JavaScript
Cookie.SameSite Lax Not sent on cross-site POSTs
Cookie.SecurePolicy None Set to Always to send it only over HTTPS
Cookie.Path / Path the cookie applies to
Cookie.IsEssential false Bypass cookie consent checks
Cookie.MaxAge not set Make the cookie persistent instead of a browser-session cookie

10. When to use sessions (and when not)

Good uses:

Avoid sessions for:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents