多个用户登录时 SignalR OnConnected 方法未触发

SignalR OnConnected method not firing when multiple users sign in

我一直在尝试使用 SignalR 向 MVC 网站添加实时通知功能。我正在使用 Asp.NET 身份验证。

据我所知,SignalR documentation 集线器上的 OnConnected 方法 class 应该在用户登录时触发。

因此,当我进行调试时,如果我对第一个用户进行签名,则 OnConnected 方法会正确调用。但是,当我打开另一个浏览器(例如:Firefox、Microsoft edge ..)并登录另一个用户时,永远不会调用 OnConnected。

我的启动 class 看起来像这样:

[assembly: OwinStartup(typeof(NotificationApp.Startup))]
namespace NotificationApp
{
  public partial class Startup
  {
      public void Configuration(IAppBuilder app)
      {
          ConfigureAuth(app);
          app.MapSignalR();
      }
  }
}

中心 class

namespace NotificationApp
{    
    [Authorize]
    public class NotificationHub : Hub {
        
        //This gets called for the first logged in user only
        public override Task OnConnected()
        {
            Clients.Client(Context.ConnectionId).connected(Context.ConnectionId);

            return base.OnConnected();
        }

       public override Task OnDisconnected(bool stopCalled)
        {
            return base.OnDisconnected(stopCalled);
        }
   }
}

客户代码


$(document).ready(function () {
    var notificationHub = $.connection.notificationHub;
    
    //Called for every client properly
    $.connection.hub.start().done(function () {

     console.log('Notification hub started');
      
    });

 //This gets called for the first logged in user only
 notificationHub.client.connected = function (message) {

        console.log('Hello' + message);
    };

});

当您打开另一个选项卡时,您是同一个客户端,然后会获得一个连接 ID。

尝试更改“客户端”:

        public override Task OnConnected()
    {
        Clients.Client(Context.ConnectionId).connected(Context.ConnectionId);

        return base.OnConnected();
    }

致“来电者”:

        public override Task OnConnected()
    {
        Clients.Caller.connected(Context.ConnectionId);

        return base.OnConnected();
    }

此外,将您的客户端功能移到 hub.start 之前。您应该始终在开始之前注册一个功能。请参阅 docs.

中有关的说明