Search code examples
api.net-corewebsocketsignalrsignalr-hub

.NetCore SignalR join group over API call


I have the following flow in mind:

A .NetCore web app, where you can create multiple groups on a hub. Mobile app where user can join a group by passing the group name. The web app can send messages to group users.

I can create and join groups from the web app, but I am not sure it is possible to do so over a controller.


Hub:

    public class VotingHub : Hub
    {

        public async Task JoinGroup(string groupName)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
            await SendMessageToGroup(groupName , $"{ Context.ConnectionId} has joined the group { groupName}.");
        }

        public async Task SendMessageToGroup(string groupName, string message)
        {
            await Clients.Group(groupName).SendAsync("ReceivedMessage", message);
        }
    }

Controller:

    public class EventsController : Controller
    {
        private IHubContext<VotingHub> _hubContext;

        public EventsController(IHubContext<VotingHub> hubContext)
        {
            _hubContext = hubContext;
        }


        [HttpGet("/join")]
        public IActionResult JoinGroup(string groupName)
        {
            _hubContext.Groups.AddToGroupAsync(** I do not have access to ConnectionId**);
            return Ok();
        }
    }

If this is not possible, what would be an alternative to implement the flow described above?


Solution

  • I believe it is possible but provably this is a not good way. As you can see, you don't have access to the connectionId to add user to the group. So the best way to do that is from the hub and the connection must invoke this method. Imagine this scenario: you have the connectionId that you want to join the group and you POST it via controller. The connection at that time could be not established or been drooped, so the connection has now another conncetionId.