sessionblazorblazor-server-sidesession-storage

Blazor Session Storage


At my current project(blazor server side) I want to start using the session storage for user data like roles and names. I've tried Blazored.SessionStorage and AspNetCore.Components.Server.ProtectedBrowserStorage. The problem I'm facing is, that I just can't get the value(it's always null) and I don't know why. Code I'm using:

public void GetUserInfo()
{
    var x = sessionStorage.GetAsync<string>("Name");
    var y = sessionStorage.GetAsync<string>("Email");
    string Name = x.ToString();
    string Email = y.ToString();
}

And

[Inject] public ProtectedSessionStorage sessionStorage { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    string Name = Helper.Name;
    string Email = Helper.Email;
    await sessionStorage.SetAsync("Name", Name);
    await sessionStorage.SetAsync("Email", Email);

    var x = sessionStorage.GetAsync<string>("Name");
    var y = sessionStorage.GetAsync<string>("Email");
    Name = x.Result.Value;
    Email = y.Result.Value;
}

Thanks to everyone in advance and have a great day! :)


Solution

  • OnAfterRenderAsync is only called the first time the page/component is rendered, and session storage items are deleted when the session ends. In other words, when you close the browser all the info you saved in session storage is removed, so when you open the application that data will of course be null, and if you navigate to another page on the site and come back the method will not be called again, only when you close and reopen the app. Instead, use the OnInitializedAsync method.

    Here is how to set it up using ProtectedBrowserStorage:

    1. In _Imports.razor (in the .Web project) add the following 2 lines of code:
    @using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
    @inject ProtectedSessionStorage ProtectedSessionStore
    

    This will make session storage available for all web pages in the app.

    1. In App.razor (Components/App.razor) you should find the below 2 tags:
    <HeadOutlet />
    <Routes />
    

    Modify the tags with rendermode like this:

    <HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
    <Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />
    
    1. Use the ProtectedSessionStore SetAsync and GetAsync methods to set and get data. Below is an example from the Blazor Aspire template "Counter" page.
    protected override async Task OnInitializedAsync()
    {
        var result = await ProtectedSessionStore.GetAsync<int>("count");
        currentCount = result.Success ? result.Value : 0;
    }
    
    private async Task IncrementCount()
    {
        currentCount++;
        await ProtectedSessionStore.SetAsync("count", currentCount);
    }
    

    You can use the set and get methods with any type you'd like. Useful official documentation: ASP.NET Core Blazor state management | Microsoft Learn