简体   繁体   English

Blazor Session 存储

[英]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.在我当前的项目(blazor 服务器端)中,我想开始使用 session 存储来存储角色和名称等用户数据。 I've tried Blazored.SessionStorage and AspNetCore.Components.Server.ProtectedBrowserStorage.我试过 Blazored.SessionStorage 和 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: :)提前感谢大家,祝你有美好的一天::)

I suggest adding this as an injected object using Dependency Injection.我建议使用依赖注入将其添加为注入的 object。

Create a class to hold this information and add is as a Scoped service.创建一个 class 来保存此信息并将其添加为 Scoped 服务。

Class: Class:

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

Injection (Program.cs on .NET 6):注入(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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM