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 seesionStorage in Blazor apps, write a custom code or use a third party package. The accessed data can be stored in the localStorage and sessionStorage.  The 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 the 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.

[startup.cs]
using Blazored.SessionStorage;

public void ConfigureServices(IServiceCollection services)
{
         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();
    }
}

Reference link: https://github.com/blazored/SessionStorage

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.