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;
. . .
. . .
. . .
. . .
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();
}
}
Share with