javascript SignalR - 使用 UserID Provider 向用户发送消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21068472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SignalR - Send message to user using UserID Provider
提问by hatcyl
Using SignalR, I believe I should be able to send messages to specific connected users by using UserID Provider
使用 SignalR,我相信我应该能够使用UserID Provider向特定连接的用户发送消息
Does anyone have an example of how this would be implemented? I've searched and searched and can not find any examples. I would need to target a javascript client.
有没有人有一个如何实施的例子?我搜索和搜索,找不到任何例子。我需要定位一个 javascript 客户端。
The use case is, users to my site will have an account. They may be logged in from multiple devices / browsers. When some event happens, I will want to send them a message.
用例是,我网站的用户将拥有一个帐户。他们可能从多个设备/浏览器登录。当某些事件发生时,我想向他们发送消息。
采纳答案by Gjohn
I have not looked into SignalR 2.0 but I think this is an extension of what the previous versions of SignalR used to have. When you connect to the hub you can decorate it with an Authorize attribute
我没有研究过 SignalR 2.0,但我认为这是对以前版本的 SignalR 的扩展。当您连接到集线器时,您可以使用 Authorize 属性对其进行装饰
[HubName("myhub")]
[Authorize]
public class MyHub1 : Hub
{
public override System.Threading.Tasks.Task OnConnected()
{
var identity = Thread.CurrentPrincipal.Identity;
var request = Context.Request;
Clients.Client(Context.ConnectionId).sayhello("Hello " + identity.Name);
return base.OnConnected();
}
}
As you can see you are able to access the Identity of the user accessing the Hub. I believe the new capability would be nothing more than an extension of this. Since the connection is always kept alive between the client and the hub you will always have the principal identity which will give you the UserId.
如您所见,您可以访问访问 Hub 的用户的身份。我相信新功能只不过是对此的扩展。由于客户端和集线器之间的连接始终保持活动状态,因此您将始终拥有主体身份,该身份将为您提供 UserId。
回答by mrtig
I believe this can help you: (linked from here)
我相信这可以帮助你:(从这里链接)
A specific user, identified by userId.
由 userId 标识的特定用户。
Clients.User(userid).addContosoChatMessageToPage(name, message);
The userId can be determined using the IUserId interface:
可以使用 IUserId 接口确定 userId:
public interface IUserIdProvider
{
string GetUserId(IRequest request);
}
The default implementation of IUserIdProvider
is PrincipalUserIdProvider
. To use this default implementation, first register it in GlobalHost
when the application starts up:
的默认实现IUserIdProvider
是PrincipalUserIdProvider
. 要使用这个默认实现,首先GlobalHost
在应用程序启动时注册它:
var idProvider = new PrincipalUserIdProvider();
GlobalHost.DependencyResolver.Register (typeof(IUserIdProvider), () => idProvider);
The user name can then be determined by passing in the Request object from the client.
然后可以通过从客户端传入 Request 对象来确定用户名。