当用户在多个浏览器选项卡上注销时,Blazor WASM需要重新验证用户身份,以防止用户在其他选项卡上执行任何操作。以下是一些步骤,可以实现此功能:
public delegate Task OnUserLogout();
public class UserState
{
public bool IsLoggedIn { get; set; }
public event OnUserLogout OnLogout;
public async Task LogoutAsync()
{
IsLoggedIn = false;
if (OnLogout != null)
{
await OnLogout();
}
}
}
[Inject]
UserState UserState { get; set; }
[Inject]
ILocalStorageService LocalStorage { get; set; }
protected override async Task OnInitializedAsync()
{
UserState.OnLogout += OnUserLogout;
if (await LocalStorage.ContainKeyAsync("loggedIn") &&
await LocalStorage.GetItemAsync("loggedIn"))
{
UserState.IsLoggedIn = true;
}
}
private async Task OnUserLogout()
{
await LocalStorage.SetItemAsync("loggedIn", false);
StateHasChanged();
}
Hello, Admin!
@code {
private HubConnection hubConnection;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/hub"))
.Build();
hubConnection.On("LoginStateChanged", async (isLoggedIn) =>
{
if (isLoggedIn)
{
await UserState.LogoutAsync();
}
});
await hubConnection.StartAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await hubConnection.SendAsync("AddUser
上一篇:BlazorWASMdoesnotdebugonRider
下一篇:Blazorwasmerror"objectreferencenotsettoaninstanceofanobject"thatmakesnosense