SignalR:在集线器上下文之外使用调用方方法

SignalR: Using the caller method outside of the hub context

我正在尝试在 Hub 上下文之外使用 Caller 方法。我有一个助手 class,它在向所有用户广播消息时工作正常,如下所示:

hub.Clients.All.newLessonAlert(notif);

它不允许我在此 class 中使用 Caller 方法,但这在集线器上下文 class 中工作正常。为什么是这样?我还尝试将我的所有函数移动到上下文 class 中,但我现在得到了这个未处理的异常:

Using a Hub instance not created by the HubPipeline is unsupported

有没有一种简单的方法可以继续使用我的助手 class 并识别与集线器的连接?

我通过以下方式解决了这个问题:

  1. 我在我的 Hub class 中创建了一个 OnConnected 方法。这将当前连接的用户分配给一个组。

    [HubName("NotificationsHub")]
    public class NotificationHub : Hub
    {
        private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
    
        public override Task OnConnected()
        {
            string userid = Context.Request.User.Identity.GetUserId();
            Groups.Add(Context.ConnectionId, userid);
            return base.OnConnected();
        }
    }
    
  2. 修改了我的 HubHelper class 现在将此警报广播给当前连接的用户(由用户 ID 指定)

    public void HighScoreAlert(int gameid, int score, string userID)
    {
        string message = "High Score achieved on " + gameid;
    
        hub.Clients.Group(userID).score(message);
    }
    
  3. 对于控制器操作,我传入了用户 ID,然后调用上面介绍的 HubHelper 方法。

希望这对某人有所帮助