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

部署至Azure App Service时SignalR连接异常断开问题求助

Azure App Service部署SignalR连接频繁断开问题排查与解决

常见原因及修复方案

1. 开启Azure App Service的WebSockets支持

SignalR默认依赖WebSockets传输,Azure App Service默认未启用该功能:

  • 登录Azure门户,进入目标App Service
  • 打开配置 > 常规设置
  • 将WebSockets选项设为启用,保存后重启服务

2. 修正后端SignalR与跨域配置

确保.NET Core后端配置适配Azure环境:

  • 跨域策略需包含前端部署的完整域名,示例Program.cs代码:
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend",
        policy => policy.WithOrigins("https://your-frontend-azure-url")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials());
});

// 注册SignalR并应用跨域策略
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<YourHub>("/your-hub-path")
             .RequireCors("AllowFrontend");
});

3. 调整前端SignalR连接配置

Angular端连接需适配Azure的HTTPS环境:

  • 使用部署后的完整HTTPS地址建立连接,避免localhost
  • 显式指定传输方式,优先WebSockets并配置降级方案,示例代码:
import { HubConnectionBuilder } from '@microsoft/signalr';

const hubConnection = new HubConnectionBuilder()
  .withUrl('https://your-app-service-url/your-hub-path', {
    transport: ['WebSockets', 'ServerSentEvents', 'LongPolling']
  })
  .build();

4. 优化连接超时设置

Azure App Service默认230秒空闲超时会断开无活动连接:

  • 后端添加心跳机制,定期向客户端发送空消息维持连接
  • 或在Azure门户配置 > 常规设置中调整空闲超时至合理时长(最长120分钟)

5. 启用详细日志定位根源

通过日志排查具体断开原因:

  • 在Azure门户开启App Service的应用日志记录和Web服务器日志,查看SignalR相关错误
  • 后端Hub类中添加连接事件日志,示例代码:
public override async Task OnConnectedAsync()
{
    _logger.LogInformation($"客户端[{Context.ConnectionId}]已连接");
    await base.OnConnectedAsync();
}

public override async Task OnDisconnectedAsync(Exception exception)
{
    _logger.LogInformation($"客户端[{Context.ConnectionId}]断开连接,异常信息:{exception?.Message}");
    await base.OnDisconnectedAsync(exception);
}

内容的提问来源于stack exchange,提问作者K.Desai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:44:53