I am using SignalR in my ASP.NET web application. Here I am calling client from outside to hub class using IHubContext
. I need to get the current user's connection ID in order to send messages to the current user only. How can I get the connection ID on the client side?
33
votes
oh ok. Is there a way to get connection id of current user in the client side?
– selvakumar
It's documented in the SignalR wiki
– khellang
Some dudes are just too mean on STACK OVERFLOW. Just give the dude a straight answer and stop redirecting the guy to a documentation. If you dont know the answer, stop responding. The guy is new to STACK. @Ruchira, thanks for ur straight forward answer. var c_id = $.connection.hub.id;
– Ifeanyi Chukwu
7 Answers
2
votes
There's another way also, you can get connection id into your controller from hub by invoking a method of hub
and you can return the required ID
from there.
Controller Code
var HubContext = GlobalHost.ConnectionManager.GetHubContext<"ChatHub">(); //`ChatHub` can be your Hub Name
ChatHub HubObj= new ChatHub();
var RequiredId= HubObj.InvokeHubMethod();
Code inside Hub
public string InvokeHubMethod()
{
return "ConnectionID" //ConnectionID will the Id as string that you want outside the hub
}
2
votes
1
votes
1
votes
Server : Context.ConnectionId => "dJSbEc73n6YjGIhj-SZz1Q"
Client :
this._hubConnection
.start()
.then(() => {
var hub = this._hubConnection ;
var connectionUrl = hub["connection"].transport.webSocket.url ;
console.log(connectionUrl);
=> wss://localhost:5001/notify?id=dJSbEc73n6YjGIhj-SZz1Q
you can extract the id. (far to be a perfect solution)
0
votes
use the following code it works for me.
in the hub class.
public static ConcurrentDictionary<string, MyUserType> MyUsers = new ConcurrentDictionary<string, MyUserType>();
public override Task OnConnected()
{
MyUsers.TryAdd(Context.User.Identity.Name, new MyUserType() { ConnectionId = Context.ConnectionId,UserName=Context.User.Identity.Name });
string name = Context.User.Identity.Name;
Groups.Add(Context.ConnectionId, name);
return base.OnConnected();
}
in the hub class file create the following class
public class MyUserType
{
public string ConnectionId { get; set; }
public string UserName { get; set; }
}
and outside the hub class.
var con = MyHub1.MyUsers;
var conId =con.Select(s => s.Value).Where(s => s.UserName == User.Identity.Name).FirstOrDefault();