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

Blazor Server应用经Application Gateway部署于App Service,频繁重连该如何处理?

Blazor Server + Azure Application Gateway 重连问题解决方案

这种情况完全可以避免,核心是让Application Gateway、Azure App Service和Blazor Server的超时配置保持匹配,而非只能靠自定义重连处理。以下是具体解决思路:

一、调整深层配置项(根本解决)

1. 修改Application Gateway的超时设置

Application Gateway默认请求超时为20秒,而Blazor Server依赖SignalR长连接,需要调大这个值:

  • 登录Azure门户,进入你的Application Gateway资源
  • 找到后端HTTP设置,选中对应设置项
  • 将请求超时调整为300秒(5分钟),同时确保连接保持时间设置合理(建议大于Blazor的SignalR心跳间隔)

2. 配置Blazor Server的SignalR超时参数

在Program.cs中调整SignalR的心跳和超时,确保心跳包能在网关超时前发送,维持连接:

builder.Services.AddServerSideBlazor()
    .AddHubOptions(options =>
    {
        // 客户端超时时间,需小于网关超时
        options.ClientTimeoutInterval = TimeSpan.FromMinutes(4);
        // 心跳间隔,建议为超时时间的1/3~1/4
        options.KeepAliveInterval = TimeSpan.FromMinutes(1);
    });

3. 调整Azure App Service的ARR超时

Azure App Service的ARR(应用请求路由)默认超时也是20秒,需要同步调整:

  • 方法一:在App Service的web.config中添加代理超时配置:
<system.webServer>
  <proxy timeout="00:05:00" /> <!-- 设置为5分钟 -->
</system.webServer>
  • 方法二:在Azure门户的App Service资源中,进入配置 > 通用设置,找到ARR超时,调整为300秒

二、自定义重连处理(优化用户体验)

如果暂时无法调整网关或服务配置,或者作为配置调整后的补充,可以自定义重连逻辑,降低对用户的干扰:
在_Host.cshtml中替换默认的重连处理:

<script src="_framework/blazor.server.js"></script>
<script>
  Blazor.start({
    reconnectionHandler: {
      onConnectionDown: () => {
        // 创建低调的提示元素
        const notice = document.createElement('div');
        notice.style.cssText = 'position:fixed;bottom:20px;left:50%;transform:translateX(-50%);padding:8px 16px;background:#333;color:white;border-radius:4px;font-size:14px;';
        notice.textContent = '连接暂时中断,正在重连...';
        document.body.appendChild(notice);

        return new Promise((resolve) => {
          const retryInterval = setInterval(async () => {
            const success = await Blazor.reconnect();
            if (success) {
              clearInterval(retryInterval);
              notice.remove();
              resolve();
            }
          }, 1000);
        });
      }
    }
  });
</script>

总结

优先通过调整各组件的超时配置来从根本上解决连接中断问题;自定义重连处理仅作为优化用户体验的辅助手段,无法替代核心配置调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 19:13:11