Hi I am using Signal R in my asp dot net web application. Here I am calling client from outside to hub class using IHubContext. I need to get current userconnection id in order to send message to current called user only.How can I get it?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
由 翻译强力驱动
问题:
回答1:
Yep. You can use $.connection.hub.id
回答2:
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 }
回答3:
This works for me:
var hub = $.connection.someHub; // After connection is started console.log(hub.connection.id);
回答4:
For a .NET Client it is on the Connection
object, inherited by HubConnection
.
Connection.ConnectionId
So typically can be found on
hubConnection.ConnectionId
回答5:
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();