Blazor Webassembly (PWA) 是否支持会话存储独立不在 asp.net 核心中托管?

问题描述

我的类中有以下代码继承自 AuthenticationStateProvider

public async override Task<AuthenticationState> GetAuthenticationStateAsync()
        {    
            if (sessionStorageService.ContainKeyAsync("UserProfile").Result)
            {
                var mAUser = await sessionStorageService.GetItemAsync<MAUser>("UserProfile");
                return await Task.Fromresult(BuildAuthenticationState(mAUser));
            }
            else
            {
                return Anonymous;
            }
        }

我在网上收到错误

if (sessionStorageService.ContainKeyAsync("UserProfile").Result)

错误是:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Cannot wait on monitors on this runtime.
System.PlatformNotSupportedException: Cannot wait on monitors on this runtime.
   at System.Threading.Monitor.ObjWait(Boolean exitContext,Int32 millisecondsTimeout,Object obj)
   at System.Threading.Monitor.Wait(Object obj,Boolean exitContext)
   at System.Threading.Monitor.Wait(Object obj,Int32 millisecondsTimeout)
   at System.Threading.ManualResetEventSlim.Wait(Int32 millisecondsTimeout,CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.SpinThenBlockingWait(Int32 millisecondsTimeout,CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.InternalWaitCore(Int32 millisecondsTimeout,CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.InternalWait(Int32 millisecondsTimeout,CancellationToken cancellationToken)
   at System.Threading.Tasks.Task`1[[System.Boolean,System.Private.CoreLib,Version=5.0.0.0,Culture=neutral,PublicKeyToken=7cec85d7bea7798e]].GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1[[System.Boolean,PublicKeyToken=7cec85d7bea7798e]].get_Result()
   at MyAushadhaBlazor.Auth.AuthStateProvider.GetAuthenticationStateAsync() in C:\xxx\xxxx\xxx\xxx\xxx\BlazorApp1\Auth\AuthStateProvider.cs:line 40
   at Microsoft.AspNetCore.Components.Authorization.AuthorizeViewCore.OnParameteRSSetAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()

解决方法

Blazor WASM 与 Blazor Server 相比,对任务调度程序的支持有限。 .GetAwaiter().GetResult() 之类的东西在 Blazor WASM 中不起作用。这解释了您的错误消息

无法在运行时

上等待监视器

如果您在 await 前面添加 ContainKeyAsync 并删除 .Result,它应该可以工作。

public async override Task<AuthenticationState> GetAuthenticationStateAsync()
{    
    if (await sessionStorageService.ContainKeyAsync("UserProfile"))
    {
        var mAUser = await sessionStorageService.GetItemAsync<MAUser>("UserProfile");
        return await Task.FromResult(BuildAuthenticationState(mAUser));
    }
    else
    {
        return Anonymous;
    }
}