我为一个可能很愚蠢的问题道歉,但我是Blazor的新手。而不是通过"认证"来添加认证;创建项目;巫师,我正在实现我自己的。
当我最初(从Visual Studio(加载站点时,在异步GetAuthenticationStateAsync方法中调用会话存储时遇到错误:
"InvalidOperationException:此时无法发出JavaScript互操作调用。这是因为组件是静态渲染的。启用预呈现后,JavaScript互操作调用只能在OnAfterRenderAsync生命周期方法期间执行">
错误很容易再现/模拟:
- 使用个人帐户创建一个普通的.NET Core 6 Blazor服务器应用程序
- 导航到Areas\Identity中的RevalidatingIdentityAuthenticationStateProvider类
用以下内容替换ctor和GetAuthenticateStateAsync:
private readonly ProtectedSessionStorage _sessionStorage;
public RevalidatingIdentityAuthenticationStateProvider(
ILoggerFactory loggerFactory,
IServiceScopeFactory scopeFactory,
IOptions<IdentityOptions> optionsAccessor,
ProtectedSessionStorage sessionStorage)
: base(loggerFactory)
{
_scopeFactory = scopeFactory;
_options = optionsAccessor.Value;
_sessionStorage = sessionStorage;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
// This will throw the error the first time it is called.
// My code does not call base, but will execute different logic based on whether
// the user is already logged in.
// This is merely to showcase the issue.
ProtectedBrowserStorageResult<bool> result = await _sessionStorage.GetAsync<bool>("username");
return base.GetAuthenticationStateAsync().Result;
}
我得到了错误,但不确定解决这个问题的最佳方法是什么?第二次调用GetAuthenticationStateAsync((时,调用_sessionStorage工作正常。是否可以检查是否可以调用_sessionStorage?有更好的方法吗?
我的代码基于几个在GetAuthenticationStateAsync中调用_sessionStorage的示例,我对它不再工作感到有点惊讶。不过,这些样本是针对旧版Blazor的,所以我相信很多事情都发生了变化。
非常感谢任何帮助/建议。
您需要在:_Host.cshtml文件中更改blazor项目中的渲染模式。
将其从"ServerPrerender"更改为"Server"。
我希望它能解决这个问题:(