Blazor 8 WASM认证实现遇渲染模式错误及解决咨询
初始错误与场景
首次在Blazor 8 WASM中实现认证时,遇到错误:
InvalidOperationException: JavaScript interop calls cannot be issued during server-side static rendering, because the page has not yet loaded in the browser. Statically-rendered components must wrap any JavaScript interop calls in conditional logic to ensure those interop calls are not attempted during static rendering
项目相关配置:
App.razor中定义:<Routes @rendermode="InteractiveWebAssembly" />Routes.razor代码:
<Router AppAssembly="@typeof(Program).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="routeData" DefaultLayout="@typeof(Layout.MainLayout)"> <NotAuthorized> <h1>Sorry!!</h1> <p> You dont have access </p> </NotAuthorized> </AuthorizeRouteView> </Found> <NotFound> <LayoutView Layout="@typeof(Layout.MainLayout)"> <p>Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router>
此前在Blazor 6中成功实现过认证,本次项目创建时选择了Interactivity location: Global,怀疑这是问题根源。
尝试修改后的新错误
将渲染模式改为InteractiveAuto后,出现新错误:
InvalidOperationException: A component of type '.Client.Routes' has render mode 'InteractiveAutoRenderMode', but the required endpoints are not mapped on the server. When calling 'MapRazorComponents', add a call to 'AddInteractiveServerRenderMode'. For example, 'builder.MapRazorComponents<...>.AddInteractiveServerRenderMode()'
随后在Program.cs中添加了InteractiveServerRenderMode,但错误仍未解决。
已完成的修改
对项目进行了如下调整:
- 在
App.razor中将HeadOutlet和Routes改为@rendermode="InteractiveAuto" - 在
Program.cs中添加服务配置:
builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddInteractiveWebAssemblyComponents();
以及端点配置:
app.MapRazorComponents<App>() .AddInteractiveServerRenderMode() .AddInteractiveWebAssemblyRenderMode() .AddAdditionalAssemblies(typeof(TerraCloud.Client._Imports).Assembly);
- 添加了自定义
AuthenticationStateProvider
疑问
请问这些修改是否正确?是否还有其他需要调整的地方?
内容的提问来源于stack exchange,提问作者MrNemeczek

