IC Improve Code Recipes

Recipe 16.3 · C#

A Typed Session Wrapper

Problem

The application stores everything in session: the user, the selected customer, the search filters, a half-finished order, sometimes a whole DataSet. Keys are strings scattered across hundreds of pages, a typo creates a new key silently, and every read is a cast that throws when the session has expired.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: magic strings, casts and object graphs.
int customerId = (int)Session["CustomerID"];   // NullReference
Session["CustomerId"] = ddlCustomer.SelectedValue; // other key

Session["SearchResults"] = dataSet;            // megabytes
var order = (Order)Session["CurrentOrder"];

The improved recipe

C#
using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.AspNetCore.Http;

namespace ImproveCode.Web.Session;

public static class SessionJsonExtensions
{
    private static readonly JsonSerializerOptions Json =
        new(JsonSerializerDefaults.Web);

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

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

public sealed record OrderDraftLine(string Sku, int Quantity);

public sealed record OrderDraft(
    int CustomerId, IReadOnlyList<OrderDraftLine> Lines);

public interface IUserSession
{
    int? SelectedCustomerId { get; set; }
    OrderDraft? OrderDraft { get; set; }
    void Clear();
}

public sealed class UserSession(IHttpContextAccessor accessor)
    : IUserSession
{
    private const string CustomerKey = "user.selectedCustomerId";
    private const string DraftKey = "user.orderDraft";

    private ISession Session =>
        accessor.HttpContext?.Session
        ?? throw new InvalidOperationException(
            "Session is only available during a request.");

    public int? SelectedCustomerId
    {
        get => Session.GetInt32(CustomerKey);
        set
        {
            if (value is int id)
            {
                Session.SetInt32(CustomerKey, id);
            }
            else
            {
                Session.Remove(CustomerKey);
            }
        }
    }

    public OrderDraft? OrderDraft
    {
        get => Session.GetJson<OrderDraft>(DraftKey);
        set
        {
            if (value is null)
            {
                Session.Remove(DraftKey);
            }
            else
            {
                Session.SetJson(DraftKey, value);
            }
        }
    }

    public void Clear() => Session.Clear();
}

Registration and pipeline:

C#
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace ImproveCode.Web.Session;

public static class SessionSetup
{
    private const string CookieName = ".App.Session";

    public static IServiceCollection AddUserSession(
        this IServiceCollection services)
    {
        // One server only. Use Redis or SQL Server in a farm.
        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(20);
            options.Cookie.Name = CookieName;
            options.Cookie.HttpOnly = true;
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.Cookie.SameSite = SameSiteMode.Lax;
            options.Cookie.IsEssential = true;
        });
        services.AddHttpContextAccessor();
        services.AddScoped<IUserSession, UserSession>();
        return services;
    }

    public static IApplicationBuilder UseUserSession(
        this IApplicationBuilder app)
    {
        app.UseSession();
        return app.Use(async (context, next) =>
        {
            if (context.Request.Cookies.ContainsKey(CookieName))
            {
                await context.Session.LoadAsync(
                    context.RequestAborted);
            }
            await next(context);
        });
    }
}

Usage snippet:

C#
public IActionResult Select(int id)
{
    userSession.SelectedCustomerId = id;
    return RedirectToAction("Index", "Invoices");
}

How it works

IUserSession is the only place that knows session keys exist. Pages and services ask for SelectedCustomerId and get an int?: null when it was never set or the session expired, never an exception. Keys are private constants, so a typo can't create a second key. Because it's an interface, a unit test can pass a simple in-memory implementation.

ASP.NET Core session stores bytes in an IDistributedCache, keyed by a cookie. SetJson and GetJson serialize small objects with System.Text.Json, which keeps them readable when you inspect the cache and makes the stored shape explicit. Records like OrderDraft serialize cleanly.

UseUserSession adds the session middleware and then loads the session asynchronously when the browser already has a session cookie. Without LoadAsync, the first access to Session loads it synchronously, which blocks a thread on a network call when the cache is Redis or SQL Server.

Variations and pitfalls

  • Session is not locked. Web Forms took an exclusive lock on session for every page that could write to it (the default), so two requests from the same user ran one after the other. ASP.NET Core doesn't. Two tabs can read the same draft, change it and write it back, and the last write wins. Keep values small and independent, and put anything that must be consistent, like an order, in the database.
  • Session is not for identity. The logged-in user belongs in the authentication cookie, not in Session["User"]. If the session expires before the auth cookie, the user should still be signed in.
  • Store IDs and small state, never DataSets or search results. Re-run the query, or cache it with IMemoryCache keyed by user (Chapter 3).
  • In a web farm, use Microsoft.Extensions.Caching.StackExchangeRedis or Microsoft.Extensions.Caching.SqlServer for the cache, and share Data Protection keys across servers, or the session cookie can't be read on the next server.
  • During a migration, an IUserSession implementation can read from the legacy app's session through the System.Web adapters (Recipe 16.6). Switch the registration when the legacy app is gone; callers don't change.