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

Azure SignalR Service拒绝将连接加入组问题求助

问题解决步骤

1. 修正服务端Azure SignalR配置

现有代码仅配置了自托管SignalR,未接入Azure SignalR服务,必须添加AddAzureSignalR扩展方法,让服务端与Azure SignalR服务交互:

// Program.cs
builder.Services.AddSignalR()
    .AddJsonProtocol(options =>
    {
        options.PayloadSerializerOptions.Converters
               .Add(new JsonStringEnumConverter());
    })
    // 新增该行,传入Azure SignalR的连接字符串(从Azure Portal获取)
    .AddAzureSignalR(builder.Configuration["AzureSignalRConnectionString"]);

// 保留原有Hub映射配置
app.MapHub<NotificationHub>("/notifications");

将Azure SignalR连接字符串配置到appsettings.json中即可。

2. 调整前端连接配置

移除skipNegotiation: true配置,Azure SignalR需要通过协商流程分配正确的连接端点和会话信息,跳过协商会导致客户端连接元数据不被Azure服务识别:

private options: signalR.IHttpConnectionOptions = {
    accessTokenFactory: () => {
        return this.userService.authToken as string;
    }
    // 移除skipNegotiation和强制transport配置,让SDK自动处理连接逻辑
};

public startConnection = () => {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(`${environment.backendApi}/notifications`, this.options)
      .configureLogging(signalR.LogLevel.Trace)
      .build();
    this.hubConnection
      .start()
      .then(() => {
          console.log("notification connection started");
          // 连接成功后再调用服务端加组方法(若为客户端主动触发场景)
          // this.hubConnection.invoke("JoinGroup", "目标组名称");
      })
      .catch(err => console.log('Error starting connection: ' + err));
}

若确实需要强制使用WebSocket,可保留transport: signalR.HttpTransportType.WebSockets,但必须删除skipNegotiation: true。

3. 确保组操作使用正确的ConnectionId

在服务端Hub中,必须使用Context.ConnectionId执行组操作,这是Azure SignalR转发的有效连接标识,禁止使用自定义或客户端传递的ID:

public async Task JoinGroup(string groupName)
{
    // 使用Context.ConnectionId而非自定义ID
    await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}

也可在OnConnectedAsync中自动完成加组,确保连接建立后立即加入目标组:

public override async Task OnConnectedAsync()
{
    // 示例:从用户Claims中获取分组标识
    var groupId = Context.User?.FindFirst("groupId")?.Value;
    if (!string.IsNullOrEmpty(groupId))
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, groupId);
    }
    await base.OnConnectedAsync();
}

4. 确认Azure SignalR服务模式

检查Azure Portal中SignalR服务实例的模式是否为Default,若误设为Serverless模式,会导致自托管Hub逻辑无法正常工作。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:51:10