Session State Migration

This sample demonstrates the SessionShim that provides Web Forms-compatible Session["key"] access in Blazor. The shim uses ASP.NET Core ISession in SSR mode and falls back to in-memory storage in interactive Blazor Server mode.


1. Setting & Getting Session Values

In Web Forms, you stored values with Session["key"] = value and retrieved them with (string)Session["key"]. The BWFC shim supports the same pattern.

Before (Web Forms)

// Store a value
Session["UserName"] = txtName.Text;

// Retrieve a value
var name = (string)Session["UserName"];

After (Blazor with BWFC)

// Same code works!
Session["UserName"] = userName;

// Retrieve a value
var name = (string)Session["UserName"];
Live Demo - Set & Get

Stored value for key "UserName": (empty)


2. Session.Count

Check how many items are currently stored in the session.

Live Demo - Count

Items in session: 0


3. Type-Safe Access with Get<T>()

The shim provides Session.Get<T>(key) for strongly-typed retrieval, avoiding manual casts.

Before (Web Forms)

// Requires manual cast
var count = (int)Session["ClickCount"];
Session["ClickCount"] = count + 1;

After (Blazor with BWFC)

// Type-safe access
var count = Session.Get<int>("ClickCount");
Session["ClickCount"] = count + 1;
Live Demo - Typed Counter

Click count (stored as int): 0


4. Clear Session

Call Session.Clear() to remove all session values, just like in Web Forms.

Live Demo - Clear

Items in session: 0


5. Setup Required

The session shim is automatically registered when you call AddBlazorWebFormsComponents(). You also need to enable the session middleware:

// Program.cs
builder.Services.AddBlazorWebFormsComponents(); // registers SessionShim + AddSession()

var app = builder.Build();
app.UseSession();                  // enable session middleware
app.UseBlazorWebFormsComponents();

Then inherit from WebFormsPageBase in your component to access Session:

@inherits WebFormsPageBase

@code {
    protected override void OnInitialized()
    {
        Session["Greeting"] = "Hello from Blazor!";
        var greeting = (string?)Session["Greeting"];
    }
}