how to get SignalR user connection id out side the

2019-04-17 20:20发布

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?

7条回答
2楼-- · 2019-04-17 20:44

For a .NET Client it is on the Connection object, inherited by HubConnection.

Connection.ConnectionId

So typically can be found on

hubConnection.ConnectionId
查看更多
该账号已被封号
3楼-- · 2019-04-17 20:53

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)

查看更多
相关推荐>>
4楼-- · 2019-04-17 20:53

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();
查看更多
男人必须洒脱
5楼-- · 2019-04-17 20:57

This works for me:

var hub = $.connection.someHub;
// After connection is started
console.log(hub.connection.id);
查看更多
狗以群分
6楼-- · 2019-04-17 21:00

Yep. You can use $.connection.hub.id.

查看更多
The star\"
7楼-- · 2019-04-17 21:00

To get the full hub url, you can say: hubConnection.connection.transport.webSocket.url

this is something like: "wss://localhost:1234/myHub?id=abcdefg"

Regex to get the ID:

var r = /.*\=(.*)/ var id = r.exec(url)[1]

查看更多
登录 后发表回答