首页 > 解决方案 > 未注册身份验证 AuthenticationStateProvider 的 Blazor Wasm 托管预渲染

问题描述

我有一个使用 Blazor WebAssembly Hosted with Authentication 的开箱即用 VS 模板,并将其转换为使用 PreRendering。但是,这样做看起来有很多服务包含在客户端中,而在服务器端没有提供。这是例外

处理请求时发生未处理的异常。InvalidOperationException:无法为类型“Microsoft.AspNetCore.Components.Authorization.CascadingAuthenticationState”的属性“AuthenticationStateProvider”提供值。没有“Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider”类型的注册服务。Microsoft.AspNetCore.Components.ComponentFactory+<>c__DisplayClass6_0.g__Initialize|2(IServiceProvider serviceProvider, IComponent 组件)

堆栈查询 Cookie 标头路由 InvalidOperationException:无法为类型“Microsoft.AspNetCore.Components.Authorization.CascadingAuthenticationState”的属性“AuthenticationStateProvider”提供值。没有“Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider”类型的注册服务。Microsoft.AspNetCore.Components.ComponentFactory+<>c__DisplayClass6_0.g__Initialize|2(IServiceProvider serviceProvider, IComponent component) Microsoft.AspNetCore.Components.ComponentFactory.PerformPropertyInjection(IServiceProvider serviceProvider, IComponent instance) Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider serviceProvider,类型 componentType) Microsoft.AspNetCore.Components.RenderTree.Renderer。

我可以在 Server startup.cs 中注册哪些服务来注册必要的服务?

标签: blazorblazor-webassemblyblazor-hosted

解决方案


所以答案是通过添加services.AddApiAuthorization();到服务器Startup.cs

这解决了缺少服务注册的问题,但是之后还有一个额外的错误。从目前的情况来看,身份验证不支持预渲染。

处理请求时发生未处理的异常。InvalidOperationException:在服务器端预呈现期间无法发出 JavaScript 互操作调用,因为页面尚未加载到浏览器中。预渲染组件必须将任何 JavaScript 互操作调用包装在条件逻辑中,以确保在预渲染期间不会尝试这些互操作调用。Microsoft.AspNetCore.Mvc.ViewFeatures.UnsupportedJavaScriptRuntime.Microsoft.JSInterop.IJSRuntime.InvokeAsync(字符串标识符,对象[] args)


推荐阅读