简体   繁体   中英

SignalR - Send message to user using UserID Provider

Using SignalR, I believe I should be able to send messages to specific connected users by using 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.

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.

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

[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.

I believe this can help you: (linked from here )

A specific user, identified by userId.

Clients.User(userid).addContosoChatMessageToPage(name, message);

The userId can be determined using the IUserId interface:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM