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

Blazor WebAssembly发布至Azure App Service后与服务器断开连接求助

Blazor WebAssembly Azure App Service 连接断开问题解决

问题根源

开发环境正常但生产环境运行一段时间后断开连接,核心原因是SignalR长连接的配置或Azure环境限制:Blazor依赖SignalR实现组件交互,Azure App Service的反向代理(ARR)、WebSocket设置、超时策略会主动中断空闲连接,而开发环境没有这类生产级限制。

解决步骤

1. 调整SignalR连接参数

在Program.cs中优化SignalR的重连和超时配置,避免连接轻易失效:

builder.Services.AddScoped(sp =>
{
    var hubUrl = new Uri($"{builder.HostEnvironment.BaseAddress}your-hub-path"); // 替换为你的Hub实际路径
    var connection = new HubConnectionBuilder()
        // 配置阶梯式自动重连策略,降低断连影响
        .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10) })
        .WithUrl(hubUrl)
        .Build();
    
    // 延长服务器超时时间,避免Azure误判连接死亡
    connection.ServerTimeout = TimeSpan.FromMinutes(5);
    // 缩短心跳发送间隔,保持连接活跃状态
    connection.KeepAliveInterval = TimeSpan.FromMinutes(2);
    
    return connection;
});

2. 修改Azure App Service ARR超时

Azure ARR默认230秒会断开长连接,需调整为更大值:

  • 登录Azure门户,进入目标App Service
  • 左侧菜单→配置→常规设置
  • 找到ARR超时,设置为1200秒(20分钟)或按需调整更长时间
  • 保存设置后重启App Service

3. 启用WebSocket支持

Blazor SignalR默认使用WebSocket传输,Azure需手动开启该功能:

  • 在App Service的配置→常规设置中
  • 将WebSocket选项设为启用
  • 保存并重启服务

4. 排查生产日志定位精准问题

通过Azure日志获取具体错误细节:

  • 进入App Service→日志→日志流,查看实时报错信息
  • 或通过**高级工具(Kudu)**→LogFiles目录,查看应用日志的详细异常栈

5. 确认发布配置无差异

  • 检查wwwroot/index.html中Blazor初始化脚本路径正确:
    <script src="_framework/blazor.webassembly.js"></script>
    
  • 确保项目csproj中SignalR包引用正常(版本匹配.NET 6):
    <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="6.0.25" />
    

临时优化用户体验

添加全局错误捕获,在断连时提示用户并提供手动重连选项:
在MainLayout.razor中使用ErrorBoundary组件:

<ErrorBoundary>
    <ChildContent>
        @Body
    </ChildContent>
    <ErrorContent>
        <div class="alert alert-danger">
            连接已断开,正在尝试重连...
            <button @onclick="() => NavigationManager.NavigateTo(NavigationManager.Uri, forceLoad: true)">
                手动刷新
            </button>
        </div>
    </ErrorContent>
</ErrorBoundary>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:30:53