Blazor 中的依赖注入在切换页面时不起作用

问题描述 投票:0回答:1

我有课

public class SessionState 
{
    public int id { get; set; }
    public bool verified { get; set; }
}

在每一页中我都在类中注入了

@inject SessionState state

我想在用户登录时填写

state.id
,我写了这段代码:

state.id = some value;
state.verified = true;
NavigationManager.NavigateTo("home");

我在

Program.cs
中有这段代码:

builder.Services.AddScoped<SessionState>();

现在,当网站导航到

Home
时,我对
state.id
没有任何价值。

我也用过这个:

builder.Services.AddSingleton<SessionState>();

但问题是当用户1登录时我有

state.id = 1
,在用户1用户2登录后我有
state.id = 2

如何为每个登录用户提供唯一的

state.id
,并且我的所有 Blazor 页面都需要它。

state.id = int.Parse(dt.Rows[0]["iduser"].ToString());
state.verified = true;
NavigationManager.NavigateTo("home");
asp.net-core dependency-injection blazor singleton scoped
1个回答
0
投票

官方文档提供了session和本地存储方式。 https://learn.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-8.0&pivots=server#server-side-storage-server

1.禁用预渲染时有效

在您的 App.razor 中

<HeadOutlet @rendermode=@(new InteractiveServerRenderMode(prerender: false)) />
<Routes @rendermode=@(new InteractiveServerRenderMode(prerender: false)) />

在你的组件中

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedSessionStorage ProtectedSessionStore
...
await ProtectedSessionStore.SetAsync("count", currentCount);
...
protected override async Task OnInitializedAsync()
{
    var result = await ProtectedSessionStore.GetAsync<int>("count");
    currentCount = result.Success ? result.Value : 0;
}

2.启用每次渲染时有效

在您的 App.razor 中

<HeadOutlet @rendermode=@(new InteractiveServerRenderMode(prerender: true)) />
<Routes @rendermode=@(new InteractiveServerRenderMode(prerender: true)) />

在你的组件中

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedSessionStorage ProtectedSessionStore
...
await ProtectedSessionStore.SetAsync("count", currentCount);
...
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        var result = await ProtectedSessionStore.GetAsync<int>("count");
        currentCount = result.Success ? result.Value : 0;
        StateHasChanged();
    }
}

每个新选项卡都与其他选项卡分开并拥有自己的存储空间

其他组件也获得该值。

Asp.net core Identity 适用于静态 SSR 渲染,经过我的测试,无论禁用/启用预渲染,它仍然不起作用,因此您可能需要自定义登录逻辑。一些相关讨论供您参考:https://github.com/dotnet/aspnetcore/issues/51476

© www.soinside.com 2019 - 2024. All rights reserved.