Inx
Inx

Reputation: 2384

Get connectionId outside of Hub, SignalR

How do I get the clients connectionId/clientId outside of the Hub?.. I have managed to do the following:

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

But in that context-object there is no such thing as a clientId.

Upvotes: 7

Views: 8804

Answers (4)

Marcos J.D Junior
Marcos J.D Junior

Reputation: 317

I changed @davidfowl comment into an answer - You send it from the client to your mvc action. It's available on the client via $.connection.hub.id

 $.connection.hub.start().done(function () { console.log($.connection.hub.id); });

And then do what ever you want with it then.

Upvotes: 1

Divya
Divya

Reputation: 1213

Here's the Solution. You can invoke a method inside the hub and you can return the connection ID from there.

In Controller

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

In Hub

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

You'll get required ID outside the hub in connectedUserID Variable. Hope This Helps.

Upvotes: 0

davidfowl
davidfowl

Reputation: 38764

Why would there be a connection Id on the global context? Which connection would it be in reference to? When you get the global context, you are accessing a one way channel from server to client and can send messages over it. You don't have access to the connection id of the hub since you aren't calling into it. You can store them somewhere in your application if you need to use them.

Upvotes: 4

WooHoo
WooHoo

Reputation: 1922

You could implement IConnected/IDisconnect on the Hub and manually keep track of clients for example in a database, then pull back the list when required. The example below is 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());
    }
}

Upvotes: 4

Related Questions