SignalR Join Group From Controller

2020-07-30 06:14发布

When the user logs in on my site, they select from a dropdown which group they belong to. On the login postback, as they are logged in, I'd like to assign them to the correct SignalR group.

As per the documentation here, I can join it client-side via:

contosoChatHubProxy.server.joinGroup(groupName);

Is there a way to assign the group from the controller? I can call the Hub like:

var hub = new NotificationHub()
hub.JoinGroup(selectedGroup);

but the Context in the hub method is null. Is this possible, or am I approaching this problem incorrectly? Thankyou for any advice.

1条回答
冷血范
2楼-- · 2020-07-30 06:37

You shouldn't new up a hub like that; you can get the hub context and add a user to a group from external code like this:

var hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
hubContext.Groups.Add(connectionId, groupName);
查看更多
登录 后发表回答