Live Chat Icon For mobile
Live Chat Icon

How do I store session data in Server-side Blazor?

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

First to access browser Session Storage in Blazor apps, write a custom code or use a third party package. The accessed data can be stored in the Local Storage and Session Storage.  The Local Storage 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 the data in the session storage will be cleared after the session. 

Use the Blazored.SessionStorage package to store the session data in Blazor. For this install the package and add the service to the application.

[Program.cs] 

using Blazored.SessionStorage; 
…
builder.Services.AddBlazoredSessionStorage();

[index.razor]

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

<h2>@Name</h2>
<button @onclick="Clear">Clear Session</button>
@code {
    public string Name;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        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();
    }
}

Share with

Related FAQs

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

Please submit your question and answer.