You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET5 Core托管WASM项目MainLayout.razor无法注入AuthenticationStateProvider

Blazor WASM托管模型AuthenticationStateProvider注入失败解决方案

问题根因

仅调用AddAuthorizationCore()只会注册授权核心服务,不会自动注册AuthenticationStateProvider的实现类,因此DI容器找不到对应服务抛出异常。

修复步骤

  • 首先确认Client项目已安装Microsoft.AspNetCore.Components.WebAssembly.Authentication NuGet包
  • 在Client项目Program.cs中补充服务注册代码,AddAuthorizationCore()之后新增如下配置:
builder.Services.AddApiAuthorization();

该方法会自动注册托管模型默认的AuthenticationStateProvider实现,对接Server端身份验证体系。

  • 验证App.razor根组件最外层包裹了<CascadingAuthenticationState>组件,示例结构如下:
<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <!-- 原有Router内部配置保持不变 -->
    </Router>
</CascadingAuthenticationState>

该组件负责将身份状态级联传递给所有子组件,是身份验证功能正常运行的必要配置。

如果你采用自定义AuthenticationStateProvider实现,无需调用AddApiAuthorization(),改为手动注册服务即可:

builder.Services.AddScoped<AuthenticationStateProvider, 你的自定义实现类名>();

内容的提问来源于stack exchange,提问作者Tarta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:24:03