Send message to specific user in signalr

All of these answers are unnecessarily complex. I simply override "OnConnected()", grab the unique Context.ConnectionId, and then immediately broadcast it back to the client javascript for the client to store and send with subsequent calls to the hub server.

public class MyHub : Hub
{
    public override Task OnConnected()
    {
        signalConnectionId(this.Context.ConnectionId);
        return base.OnConnected();
    }

    private void signalConnectionId(string signalConnectionId)
    {
        Clients.Client(signalConnectionId).signalConnectionId(signalConnectionId);
    }
}

In the javascript:

$(document).ready(function () {

    // Reference the auto-generated proxy for the SignalR hub. 
    var myHub = $.connection.myHub;

    // The callback function returning the connection id from the hub
    myHub.client.signalConnectionId = function (data) {
        signalConnectionId = data;
    }

    // Start the connection.
    $.connection.hub.start().done(function () {
        // load event definitions here for sending to the hub
    });

});

In order to be able to get "Context.User.identity.Name", you supposed to integrate your authentication into OWIN pipeline.

More info can be found in this SO answer: https://stackoverflow.com/a/52811043/861018


Keep connectionId with userName by creating a class as we know that Signalr only have the information of connectionId of each connected peers.

Create a class UserConnection

Class UserConnection{
  public string UserName {set;get;}
  public string ConnectionID {set;get;}
}

Declare a list

List<UserConnection> uList=new List<UserConnection>();

pass user name as querystring during connecting from client side

$.connection.hub.qs = { 'username' : 'anik' };

Push user with connection to this list on connected mthod

public override Task OnConnected()
{
    var us=new UserConnection();
    us.UserName = Context.QueryString['username'];
    us.ConnectionID =Context.ConnectionId;
    uList.Add(us);
    return base.OnConnected();
}

From sending message search user name from list then retrive the user connectionid then send

var user = uList.Where(o=>o.UserName ==userName);
if(user.Any()){
   Clients.Client(user.First().ConnectionID ).sendMessage(sendFromId, userId, sendFromName, userName, message);
}

DEMO