3

I can't send a notification message to a specific user from the controller.

My controller:

public class SomeController : ControllerBase
{
    private readonly IHubContext<NotificationHub> _hubContext;
    public SomeController(IHubContext<NotificationHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public async Task SomeMethod()
    {

        //it works 
        await _hubContext.Clients.All.SendAsync("sendMessage", msg);

        //it doesn't work
        await _hubContext.Clients.User(userId).SendAsync("sendMessage", msg);
        //it also doesn't work 
        await _hubContext.Clients.Client(userId).SendAsync("sendMessage", msg);
    }
}

Unfortunately, IHubContext has some imperfections. In the Clients property is available only Clients. All - that is, we can send a message only to all clients and there are no such properties as Other or Caller that are available in the hub class. Also, we cannot get a connection id from IHubContext.

Is there some else method to do it? Or is it possible only with SQL Dependency?

Zeeshan Adil
  • 1,937
  • 5
  • 23
  • 42
Ivanka
  • 53
  • 4
  • Maybe you use invalid userId? Check the post: https://stackoverflow.com/questions/19522103/signalr-sending-a-message-to-a-specific-user-using-iuseridprovider-new-2-0 – Grzesiek Danowski Apr 11 '19 at 09:36
  • hey, are you using SignalR core? – Zeeshan Adil Apr 11 '19 at 11:43
  • Yes, i'm using SignalR Core – Ivanka Apr 11 '19 at 11:52
  • 1
    @Ivanka as far as I remember Signal R core only stores the connection Ids in it so there shouldn't be any user id there. The solutions you may go for maintain a list of connected users with their connection ids, cause you should know that one user can have multiple connection ids as he/she may be connected to the hub from different clients. but that may not be a good choice if you are in a server farm in an API. if you are in a server farm the best scenario is to add every connected user to a group named after user's unique name (i.e email) did you get an idea now? – Zeeshan Adil Apr 11 '19 at 12:26
  • I would go for a Dictionary with a hashset inside it instead of a list if I wasn't in a server farm – Zeeshan Adil Apr 11 '19 at 12:27
  • During onConnect you will get connectionid. Add Userid query string. So you will receive both connectionid and userid. Save it to a dictionary collection. So if you want to send a message to specific user, just go through dictionary and find corresponding connectionid and send your message to that connectionid. – timblistic Apr 11 '19 at 13:20

0 Answers0