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

Blazor WebAssembly部署后Swagger与Hangfire路由异常排查

问题根源
  1. 路由顺序错误:Blazor的MapFallbackToFile("index.html")会接管所有未匹配的请求,若Swagger、Hangfire的路由映射放在fallback之后,这些请求会被Blazor拦截,直接跳转到404页面。
  2. 重复注册Hangfire Dashboard:同时调用app.UseHangfireDashboard和app.MapHangfireDashboard会导致路由冲突,引发异常跳转。
  3. 缓存策略冲突:生产环境下浏览器会缓存Blazor的index.html,导致访问Swagger/Hangfire时加载的是缓存的Blazor页面,必须强制刷新才能获取正确内容。
解决方案

1. 修正服务器端路由与中间件顺序

调整代码执行顺序,确保API、Swagger、Hangfire的路由优先于Blazor fallback被匹配,同时移除重复的Hangfire注册:

服务注册部分

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "my api", Version = "v1" });
});
// 注册Hangfire服务(根据你的存储配置调整)
builder.Services.AddHangfire(config => 
    config.UseSqlServerStorage(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddHangfireServer();
builder.Services.AddRazorPages();

中间件与路由映射部分(关键顺序)

// 生产环境如需启用Swagger,保留此判断(自行控制开关)
if (app.Environment.IsDevelopment() || true)
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "my api v1");
    });
}

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

app.UseRouting();
app.UseAuthorization();

// 先映射所有API、Hangfire、Razor Pages路由
app.MapControllers();
app.MapHangfireDashboard("/hangfire", new DashboardOptions
{
    Authorization = new[] { new DashboardUiFilter() }
});
app.MapRazorPages();

// 最后注册Blazor的fallback路由,确保前面的路由优先匹配
app.MapFallbackToFile("index.html");

2. 配置缓存策略,避免Swagger/Hangfire页面被缓存

修改UseStaticFiles的配置,对Swagger和Hangfire路径禁用缓存:

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        var requestPath = ctx.Context.Request.Path;
        // 对Swagger和Hangfire路径禁用缓存
        if (requestPath.StartsWithSegments("/swagger") || requestPath.StartsWithSegments("/hangfire"))
        {
            ctx.Context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
            ctx.Context.Response.Headers.Append("Pragma", "no-cache");
            ctx.Context.Response.Headers.Append("Expires", "0");
        }
        else
        {
            // 其他静态资源设置长期缓存(可选)
            ctx.Context.Response.Headers.Append("Cache-Control", "public, max-age=31536000");
        }
    }
});

3. 客户端路由验证

你现有客户端的<Found>和<NotFound>逻辑无需修改,问题核心在服务器端路由优先级配置。

验证步骤
  1. 清理项目的bin和obj目录,重新发布到生产环境/IIS。
  2. 直接访问/swagger或/hangfire,无需强制刷新即可正常加载。
  3. 点击Swagger/Hangfire内的链接,不会再被Blazor重定向到错误地址页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:13:25