3

We are using Blazor server application for our web application. We need to maintain different session values in different tabs or different browser windows.

We have already tried using local storage.

What is correct way to maintain different user values for different user instance. Meaning we need to store different values selected by same user in different browser tabs or browser windows?

Regards, Rohan

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rohan
  • 49
  • 2
  • Possible duplicate question: https://stackoverflow.com/questions/67938642/blazor-server-how-to-persist-data-across-multiple-tabs-and-refreshes –  Jun 24 '21 at 08:33
  • 1
    Do you want to maintain state across a browser window reload - F5 for example? If not then look at a Blazor Scoped Service with `OwningComponentBase`. – MrC aka Shaun Curtis Jun 25 '21 at 11:24

1 Answers1

1

In .net core 5+ you can use ProtectedStorage, note that Protected Browser Storage relies on ASP.NET Core Data Protection and is only supported for Blazor Server apps.

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedSessionStorage ProtectedSessionStore

then setter :

    private async Task IncrementCount()
{
    currentCount++;
    await ProtectedSessionStore.SetAsync("count", currentCount);
}

and getter :

    protected override async Task OnInitializedAsync()
{
    var result = await ProtectedSessionStore.GetAsync<int>("count");
    currentCount = result.Success ? result.Value : 0;
}

protected local Storage is scoped to the browser's window. If the user reloads the page or closes and re-opens the browser, the state persists. If the user opens multiple browser tabs, the state is shared across the tabs. Data persists in protected local Storageuntil explicitly cleared. protected session Storage is scoped to the browser tab. If the user reloads the tab, the state persists. If the user closes the tab or the browser, the state is lost. If the user opens multiple browser tabs, each tab has its own independent version of the data. Generally, protected session Storageis safer to use. protected session Storage avoids the risk that a user opens multiple tabs.

Ali Borjian
  • 941
  • 10
  • 18