access Context.ConnectionID outside of hub in SignalR

Viewed 928

I want to be able to send message to specific user account with SignalR.
Right now I can send to everyone!
I am looking for any way to have access to context.ConnectionID in controller outside of hub. I tried accessing it inside of controller with iHubContext and inside of hub I tried to save value of connectionID in session but both are not supported.

What would be best way to access connectionID from Controller outside of Hub?

here is action method from ChatController that is used for sending message to everyone

public IActionResult PosaljiPoruku()
    {
        _hubContext.Clients.All.SendAsync("PrimljenaPoruka", "aaa");
        return PartialView("SubmitFormPartial");
    }

Any help is appreciated!
Thanks for trying to help!

1 Answers

What would be best way to access connectionID from Controller outside of Hub?

From this doc about sending messages from outside a hub, you would find:

When hub methods are called from outside of the Hub class, there's no caller associated with the invocation. Therefore, there's no access to the ConnectionId, Caller, and Others properties.

I want to be able to send message to specific user account with SignalR.

You can mapping user and ConnectionId(s) while client connected to Hub server, then if you want to send message to specific user from controller action outside of your Hub, you can query mapping table to get corresponding connection Id(s) first based on user name etc, and passing connection Id(s) to action method.

await _hubContext.Clients.Client("connection_id_here").SendAsync("PrimljenaPoruka", "aaa");

Besides, you can achieve same by creating single-user group (a group for each user), and then send a message to that group when you want to reach only that specific user.

await _hubContext.Clients.Group("group_name_here").SendAsync("PrimljenaPoruka", "aaa");
Related