Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 847
hatcyl Avatar asked Nov 01 '22 07:11

hatcyl


1 Answers

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.

like image 74
Gjohn Avatar answered Nov 15 '22 04:11

Gjohn