You need to enable JavaScript to run this app. .NET 5 Blazor 混合架构(Server/WebAssembly)默认Identity认证实现咨询
优惠活动
大模型
产品
解决方案
定价
更多

.NET 5 Blazor 混合架构(Server/WebAssembly)默认Identity认证实现咨询

问题核心原因

你遇到的类型转换错误,本质是把Wasm客户端专属的认证服务注册逻辑错误引入了服务器端的依赖注入容器:

  • services.AddApiAuthorization()是专为Blazor WebAssembly的浏览器端Host设计的扩展方法,用来在客户端注册IRemoteAuthenticationService、远程认证状态提供器等浏览器专属组件,完全不适合在服务器端的ASP.NET Core Host中调用。
  • 当你在服务器Startup里调用这个方法时,它会打乱Server-side Blazor原有的认证服务映射,把原本的ServerAuthenticationStateProvider(服务端认证状态提供器)的服务注册替换成Wasm专属的类型定义,最终触发强制转换失败的报错。
  • 之前遇到的带[Authorize]接口返回登录跳转地址的问题,是因为未配置JWT认证的异常响应,默认会把API请求的未认证状态重定向到登录页而非返回401状态码。
修复步骤

1. 调整Server端Startup配置

删除所有Wasm专属的服务注册,保留服务器端运行必需的Identity、IdentityServer、Blazor Server相关配置,修正后的完整配置如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddDatabaseDeveloperPageExceptionFilter();
    // 保留服务器端登录/注册等Identity Razor页面
    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    // 保留内置IdentityServer,用于Wasm端token签发、API验签
    services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
    // 保留JWT认证配置,补充API未认证时返回401而非重定向
    services.AddAuthentication()
        .AddIdentityServerJwt(options =>
        {
            options.Events.OnChallenge = context =>
            {
                // 阻止API请求被重定向到登录页
                context.HandleResponse();
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                return Task.CompletedTask;
            };
        });
    
    // 注册Server-side Blazor核心服务
    services.AddServerSideBlazor();

    // 手动注册.NET 5 Server-side Blazor需要的Scoped HttpClient
    services.AddScoped(sp =>
    {
        var uriHelper = sp.GetRequiredService<NavigationManager>();
        return new HttpClient { BaseAddress = new Uri(uriHelper.BaseUri) };
    });

    services.AddControllersWithViews();
    services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseMigrationsEndPoint();
        app.UseWebAssemblyDebugging();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseBlazorFrameworkFiles();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseIdentityServer();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllers();
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
    });
}

注意:一定要删掉原来Startup里的services.AddApiAuthorization()调用,这是报错的核心来源。

2. 修正Client端Wasm入口配置

原来的Program.cs逻辑基本正确,因为这个文件是Wasm模式的浏览器端入口,所有服务注册都跑在浏览器的独立DI容器里,和服务器端DI完全隔离,只需要确保没有同步逻辑就行,修正后的代码如下:

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("#app");

    builder.Services.AddHttpClient("BlazorSwitchWithSec2.ServerAPI", 
        client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
        .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

    builder.Services.AddScoped(sp => 
        sp.GetRequiredService<IHttpClientFactory>()
        .CreateClient("BlazorSwitchWithSec2.ServerAPI"));

    // 这个AddApiAuthorization是Wasm Host的扩展,注册在浏览器端DI里,完全合规
    builder.Services.AddApiAuthorization();

    await builder.Build().RunAsync();
}

3. 修正_Host.cshtml的脚本加载逻辑

原来的代码不管运行模式都加载了Wasm专属的认证脚本,会导致Server-side模式下的脚本冲突,需要把Wasm相关的脚本放到对应模式的分支里,修正后的代码如下:

@page "/"
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    @if (Context.Request.Query["mode"] == "client")
    {
        <title>WebApp (CE)</title>
    }
    else
    {
        <title>WebApp (SE)</title>
    }
    <base href="~/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/app.css" rel="stylesheet" />
</head>
<body>
    @if (Context.Request.Query["mode"] == "client")
    {
        <component type="typeof(BlazorSwitchWithSec2.Client.App)" render-mode="WebAssemblyPrerendered" />
        <%-- 仅Wasm模式加载专属认证脚本、Wasm运行时 --%>
        <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
        <script src="_framework/blazor.webassembly.js"></script>
        <script>navigator.serviceWorker.register('service-worker.js');</script>
    }
    else
    {
        <component type="typeof(BlazorSwitchWithSec2.Client.App)" render-mode="Server" />
        <%-- Server模式仅加载Server-side运行时,不需要Wasm专属脚本 --%>
        <script src="_framework/blazor.server.js"></script>
    }
</body>
</html>
运行说明

修正完成后,同一份Client组件代码可以在两种模式下复用:

  • 不带mode=client参数访问时,会走Server-side Blazor模式,认证流程基于服务器端Cookie,直接通过SignalR连接获取认证状态
  • 带?mode=client参数访问时,会走Wasm模式,认证流程通过浏览器端远程认证服务完成,token存在浏览器本地,请求WebAPI时自动附带认证头

注意:两种模式下的登录、注册等认证页面都是服务器端的Razor Pages,不需要单独实现Wasm端的登录页面,复用内置的Identity页面即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 08:54:01