Get connectionId outside the hub, SignalR

How do I get clientId / clientId clients outside the hub? .. I was able to do the following:

var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); 

But in this context object, there is no such thing as clientId .

+6
source share
3 answers

You can implement IConnected / IDisconnect on a hub and manually track clients, for example, in a database, and then cancel the list if necessary. Below is an example from the SignalR Wiki

 public class Status : Hub, IDisconnect, IConnected { public Task Disconnect() { return Clients.leave(Context.ConnectionId, DateTime.Now.ToString()); } public Task Connect() { return Clients.joined(Context.ConnectionId, DateTime.Now.ToString()); } public Task Reconnect(IEnumerable<string> groups) { return Clients.rejoined(Context.ConnectionId, DateTime.Now.ToString()); } } 
+4
source

Why should there be a connection identifier in a global context? Which connection would be appropriate? When you get the global context, you gain access to the one-way channel from the server to the client and can send messages to it. You do not have access to the hub connection identifier because you are not calling it. You can store them somewhere in your application if you need to use them.

+4
source

Here is the solution. You can call the method inside the hub , and you can return the connection ID from there.

In the controller

 var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); MyHub _connectedHub= new MyHub(); var connectedUserID = _connectedHub.GetConnectionID(); 

In the hub

 public string GetConnectionID() { return "Your Connection ID as String" //This can be stored in a list or retrieved in any other method } 

You will receive the required ID outside the hub in the connectedUserID Variable variable. Hope this helps.

+1
source

Source: https://habr.com/ru/post/915790/


All Articles