IC Improve Code Recipes

Recipe 17.4 · C#

One Home for Session State Instead of 223 Copies

Problem

Almost every CFATS page needs the current user, the current menu and the currently selected facility. Each page gets them the same way: it declares its own properties over Session. I counted 223 code-behind files that declare a CurrentUserInfo property over Session["CurrentUserInfo"]. There are two base page classes in the project, BasePage and PageBase. Only three pages inherit from either of them. The other 291 derive straight from System.Web.UI.Page.

The way it's often written

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

From CFATS Manager, abridged to two of the 16 properties on the incident input page.

C#
// From CFATS Manager: CFATS\IncidentInput.aspx.cs
// lines 19-56 (abridged)
public partial class IncidentInput : System.Web.UI.Page
{
    #region Page Properties 16
    protected UserInfo CurrentUserInfo
    {
        set
        {
            this.Session["CurrentUserInfo"] = value;
        }
        get
        {
            return (UserInfo)this.Session["CurrentUserInfo"];
        }
    }

    protected Facility CurrentFacility
    {
        set
        {
            this.Session["CurrentFacility"] = value;
        }
        get
        {
            return (Facility)this.Session["CurrentFacility"];
        }
    }
    // ... 14 more, over Session and ViewState

Each page then repeats SetMasterPageVariables(), which copies ten values from these objects to the master page, and its own "if the facility is null" check. Change a session key, or the type stored under one, and you have 223 files to edit. A page that forgets the null check throws NullReferenceException when a session expires.

The unused base classes tell their own story. PageBase was written to solve exactly this, and it has the right properties. It also has two copy-paste bugs where a getter returns the wrong field. Nobody noticed, because almost nothing used it. A base class has to be adopted when it is created. A base class added in year three is adopted by the next page written, and by nothing else.

The improved recipe

For ASP.NET Core (Razor Pages). No packages beyond the shared framework.

C#
using System;
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Http;

namespace ImproveCode.Cfats.Web;

// Small, serializable facts about the user's current selection.
public sealed record FacilitySelection(
    int FacilityId, string FacilityName, string Status);

public interface ICurrentContext
{
    int UserId { get; }
    int ClientId { get; }
    FacilitySelection? Facility { get; }
    void SelectFacility(FacilitySelection facility);
}

public sealed class HttpCurrentContext(IHttpContextAccessor accessor)
    : ICurrentContext
{
    private const string FacilityKey = "cfats.facility";

    private HttpContext Http => accessor.HttpContext
        ?? throw new InvalidOperationException("No HTTP request.");

    public int UserId => ClaimAsInt(ClaimTypes.NameIdentifier);
    public int ClientId => ClaimAsInt("client_id");

    public FacilitySelection? Facility
    {
        get
        {
            string? json = Http.Session.GetString(FacilityKey);
            return json is null
                ? null
                : JsonSerializer.Deserialize<FacilitySelection>(json);
        }
    }

    public void SelectFacility(FacilitySelection facility)
    {
        ArgumentNullException.ThrowIfNull(facility);
        Http.Session.SetString(
            FacilityKey, JsonSerializer.Serialize(facility));
    }

    private int ClaimAsInt(string type)
    {
        string? value = Http.User.FindFirstValue(type);
        return int.TryParse(value, out int n)
            ? n
            : throw new InvalidOperationException(
                $"Claim '{type}' is missing or invalid.");
    }
}

A page filter makes "a facility must be selected" a single rule:

C#
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace ImproveCode.Cfats.Web;

[AttributeUsage(AttributeTargets.Class)]
public sealed class AllowWithoutFacilityAttribute : Attribute;

// Runs before every Razor Page handler: the one place that
// decides what happens when no facility has been chosen.
public sealed class RequireFacilityFilter(ICurrentContext current)
    : IAsyncPageFilter
{
    public Task OnPageHandlerSelectionAsync(
        PageHandlerSelectedContext context) => Task.CompletedTask;

    public async Task OnPageHandlerExecutionAsync(
        PageHandlerExecutingContext context,
        PageHandlerExecutionDelegate next)
    {
        bool exempt = context.HandlerInstance.GetType()
            .IsDefined(typeof(AllowWithoutFacilityAttribute), true);

        if (!exempt && current.Facility is null)
        {
            context.Result = new RedirectToPageResult("/FacilitySelect");
            return;
        }

        await next();
    }
}

Registration, as a usage snippet:

C#
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace ImproveCode.Cfats.Web;

public static class CurrentContextRegistration
{
    public static IServiceCollection AddCfatsContext(
        this IServiceCollection services)
    {
        services.AddHttpContextAccessor();
        services.AddDistributedMemoryCache();
        services.AddSession(o =>
        {
            o.IdleTimeout = TimeSpan.FromMinutes(20);
            o.Cookie.HttpOnly = true;
            o.Cookie.IsEssential = true;
        });
        services.AddScoped<ICurrentContext, HttpCurrentContext>();
        services.AddScoped<RequireFacilityFilter>();
        services.AddRazorPages(o =>
            o.Conventions.ConfigureFilter(
                new ServiceFilterAttribute(typeof(RequireFacilityFilter))));
        return services;
    }
}

Call app.UseSession() after UseRouting() and before MapRazorPages().

How it works

Identity moves out of session. The user ID and client ID are claims on the authentication cookie, signed and checked on every request. The original kept a whole UserInfo object in session, including login, permissions and contact details. Session keeps only what is truly session-scoped: the facility the user picked. It is stored as a small JSON record, not a serialized object graph, so a deploy that changes the Facility class can't break every live session.

Pages ask for ICurrentContext by injection. They never see a session key, so there is one place to change one. The filter replaces 200 null checks: a page that can be opened without a facility opts out with [AllowWithoutFacility], and every other page is protected by default. "Safe unless you opt out" is the property PageBase never had.

The ten values copied to the master page each time become a view component or a layout that injects ICurrentContext itself.

Variations and pitfalls

  • Don't store models in session. The original put Facility, UserInfo, MenuInfo and even the Incident being edited in session. That is fine with in-process session on one server and breaks on a web farm or after a recycle. Store IDs and reload.
  • ViewState properties. Many of the 16 properties were over ViewState. In Razor Pages those become hidden fields or route values. Protect anything security-relevant with IDataProtector or, better, look it up again on the server.
  • Multiple tabs. A facility in session is shared by every tab. If users compare facilities side by side, put the facility ID in the route (/facility/{id}/incidents) and check access in the filter.

On .NET Framework

You can stop the copying today, before any migration. Create one base page, move the properties into it, and change the Inherits of each page as you touch it. Builds against net472:

C#
using System;
using System.Web.UI;

namespace ImproveCode.Cfats.Web;

[Serializable]
public sealed class FacilitySelection
{
    public int FacilityId { get; set; }
    public string FacilityName { get; set; } = "";
}

public abstract class CfatsPage : Page
{
    private const string FacilityKey = "CurrentFacility";

    protected virtual bool RequiresFacility => true;

    protected FacilitySelection? CurrentFacility
    {
        get => Session[FacilityKey] as FacilitySelection;
        set => Session[FacilityKey] = value;
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (RequiresFacility && CurrentFacility is null)
        {
            // endResponse: true stops this page's lifecycle here,
            // so Page_Load never runs without a facility.
            Response.Redirect("~/FacilitySelect.aspx", true);
        }
    }
}

as instead of a cast means an expired session gives null, not InvalidCastException.