Search code examples
entity-frameworkasp.net-coresignalrsignalr-hub

SignalR sending notification to a specific client it's not working


When sending a notification with SignalR to a specific user it's not working.

I'm storing connection IDs in a table and when the notification should be sent I get the connection ID for the receiver from the DB but he doesn't get anything. What is wrong with my code?

// get the connectionId of the receiver
if (_db.UserConnectionid != null)
{
    var userConn = await _db.UserConnectionid.Where(x => x.UserId == receiver).Select(x => x.ConnectionId).FirstOrDefaultAsync();

    //if the receiver is online
    if (userConn != null)
    {
        await Clients.Client(userConn).SendAsync("RecieveMessage", message);
    }
}

Solution

  • I'm storing connection IDs in a table and when the notification should be sent I get the connection ID for the receiver from the DB but he doesn't get anything. What is wrong with my code?

    Firstly, please note that a user could have more than one connection id, to troubleshoot the issue, you can try to debug the code and make sure the connection id you retrieved from db is same as the one of current connecting user.

    Besides, to send message to a specific user, you can try to get all stored connection id(s) of a specific user/receiver, then send message by specify connectionIds, like below.

    var ConnectionIds = _db.UserConnectionid.Where(x => x.UserId == receiver).Select(x => x.ConnectionId).ToList();
    
    if (ConnectionIds.Count > 0)
    {
        await Clients.Clients(ConnectionIds).SendAsync("RecieveMessage", message);
    }