Live Chat Icon For mobile
Live Chat Icon

How do I store session data in Blazor WebAssembly?

Platform: Blazor| Category : General, Lifecycle, WebAssembly, Web API

As opposed to how session cookies work, when opening a page in a new tab or window, a new session occurs with the browsing context. To access the browser sessionStorage in Blazor apps, write custom

code or use a third-party package. The accessed data can be stored in localStorage and sessionStorage. Know that localStorage is scoped to the user’s browser. If the user reloads the page or closes and reopens the browser, the state persists. Session storage is similar to local storage, but data in the session storage will be cleared after the session.

Install the Blazored.SessionStorage Nuget package in the NuGet package manager to store the session data in Blazor. Add the Blazored SessionStorage configuration to the WebAssembly app.

[Program.cs]

using Blazored.SessionStorage;
. . .
. . .

public class Program
    {
        public static async Task Main(string[] args)
        {
            . . .
            . . .

            builder.Services.AddBlazoredSessionStorage();
            
        }
    }

[Index.razor]

@page "/"
@inject Blazored.SessionStorage.ISessionStorageService sessionStorage

<h2>@Name</h2>
<button class="btn btn-primary" @onclick="Clear">Clear Session</button>
@code {
    public string Name;
    protected override async Task OnInitializedAsync()
    {
        await sessionStorage.SetItemAsync("ID", "20019");
        await sessionStorage.SetItemAsync("Name", "John Smith");
        Name = "ID: " + await sessionStorage.GetItemAsync<string>("ID") + "Name : " + await sessionStorage.GetItemAsync<string>("Name");
    }
    public async void Clear()
    {
        //this will clear the session data
        await sessionStorage.ClearAsync();
    }
}

Refer to the GitHub SessionStorage repository for more details.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.