在Blazor Wasm项目中集成Azure B2C时遇运行时包错误
解决Blazor WebAssembly集成Azure B2C时的RuntimeIdentifier错误
问题根源
你遇到的错误核心原因是:Microsoft.Identity.Web.UI仅支持服务器端ASP.NET Core场景(如Blazor Server、MVC),完全不兼容Blazor WebAssembly的browser-wasm运行时;同时直接引用Microsoft.Identity.Web也不是Blazor WASM集成Azure B2C的正确方式。
解决步骤
1. 移除不兼容的包引用
打开项目文件,删除以下两个PackageReference:
<PackageReference Include="Microsoft.Identity.Web" Version="2.6.1" /> <PackageReference Include="Microsoft.Identity.Web.UI" Version="2.6.1" />
2. 添加Blazor WASM专用认证包
添加官方为Blazor WASM提供的OAuth2/OIDC认证适配包,它完美支持Azure B2C:
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="8.0.1" />
3. 修正后的完整项目文件
修改后的项目文件如下:
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <_ContentIncludedByDefault Remove="wwwroot\appsettings.json" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.1" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="8.0.1" PrivateAssets="all" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="8.0.1" /> </ItemGroup> </Project>
4. 配置Azure B2C认证逻辑
在Program.cs中添加认证配置,替换为你的Azure B2C租户信息:
builder.Services.AddOidcAuthentication(options => { builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions); options.ProviderOptions.ResponseType = "code"; // 可选:添加需要的权限范围 options.ProviderOptions.Scope.Add("offline_access"); });
同时在wwwroot/appsettings.json中添加Azure B2C配置:
{ "AzureAdB2C": { "Authority": "https://你的租户名.b2clogin.com/你的租户名.onmicrosoft.com/B2C_1_你的注册登录策略名", "ClientId": "你的应用客户端ID", "ValidateAuthority": false } }
5. 添加认证UI组件
Blazor WASM自带认证相关UI组件,无需依赖Microsoft.Identity.Web.UI:
- 在
MainLayout.razor中添加登录状态组件:
<header> <LoginDisplay /> </header>
- 在
App.razor中添加未认证重定向逻辑:
<CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"> <NotAuthorized> <RedirectToLogin /> </NotAuthorized> </AuthorizeRouteView> </Found> <NotFound> <PageTitle>Not found</PageTitle> <LayoutView Layout="@typeof(MainLayout)"> <p role="alert">抱歉,该地址不存在内容。</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState>
6. 验证修复
执行以下命令确保错误消失:
dotnet clean dotnet restore dotnet build
内容的提问来源于stack exchange,提问作者micex
相关产品推荐
相关产品推荐

