在我當前的專案(blazor 服務器端)中,我想開始使用會話存盤來存盤角色和名稱等用戶資料。我試過 Blazored.SessionStorage 和 AspNetCore.Components.Server.ProtectedBrowserStorage。我面臨的問題是,我無法獲得值(它始終為空)而且我不知道為什么。我正在使用的代碼:
public void GetUserInfo()
{
var x = sessionStorage.GetAsync<string>("Name");
var y = sessionStorage.GetAsync<string>("Email");
string Name = x.ToString();
string Email = y.ToString();
}
和
[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;
}
提前感謝大家,祝您有美好的一天!:)
uj5u.com熱心網友回復:
我建議使用依賴注入將其添加為注入物件。
創建一個類來保存此資訊,并將其添加為 Scoped 服務。
班級:
public class UserInfo : IUserInfo //Create an interface
{
public static Name { get; set; }
public static Email { get; set; }
}
注入(.NET 6 上的 Program.cs):
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
}
向注入的服務添加資料:
[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;
}
使用示例:
@inject IUserInfo UserInfo
@page "/"
<div>@UserInfo.Name</div>
<div>@UserInfo.Email</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/512124.html
下一篇:在PHP中檢查用戶會話
