Home > Software engineering >  Blazor Session Storage
Blazor Session Storage

Time:10-01

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! :)

CodePudding user response:

I suggest adding this as an injected object using Dependency Injection.

Create a class to hold this information and add is as a Scoped service.

Class:

public class UserInfo : IUserInfo //Create an interface
{
    public static Name { get; set; }
    public static Email { get; set; }
}

Injection (Program.cs on .NET 6):


public static async Task Main(string[] args)
{
    //For WSAM
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    //For Server
    var builder = WebApplication.CreateBuilder(args);
    ...
    builder.Services.AddScoped<IUserInfo, UserInfo>(); //Scoped Service injection
}

Add data to injected service:

[Inject]
public IUserInfo UserInfo { get; set; }

protected override void OnInitialized() //Use whatever Life Cycle methods works for your implementation
{
    UserInfo.Name = Helper.Name;
    UserInfo.Email = Helper.Email;
}

Usage example:

@inject IUserInfo UserInfo
@page "/"

<div>@UserInfo.Name</div>
<div>@UserInfo.Email</div>

  • Related