0
votes

I have an ASP.NET Core site where I implemented a Hub, called NotificationHub:

public interface INotificationHub
{      
    Task SendNotificationMessage(NotificationMessage message);
}

public class NotificationHub : Hub<INotificationHub>
{    
     public async Task SendMessage(NotificationMessage message)
     {          
        await Clients.All.SendNotificationMessage(message);
     }
}

I have two winforms clients that can successfully connect to the Hub and send/receive messages. I also have a page on my website that can send messages through the HubContext that is injected into my controller.

   await _hubContext.Clients.All.SendNotificationMessage(new NotificationMessage { "some message"  });

Ideally what I'd like is to send a message to a particular client and not all of the clients. I know that when a client connects I have the Context.ConnectionId available in the OnConnectedAsync method, but I'm not sure how to map that so I can route certain messages only to certain clients from a Controller (or javascript). i.e. A certain activity happens on my web site, I want to notify only one client of that and not the other.

1
First things first. Your clients have an associated user logged in ? It can be anonymous? What are the terms in which this notification takes place?Nick Polyderopoulos
if clients are logged in users, you may define a dictionary that contains connected clients connectionId values, associated with the logged in username or id. or you may add additional field to save connectionId to the users table, but in this case you have to update the related db field after each connection drop.LazZiya
I don't have any security as of set, as I'm not sure how to implement. I've read about using JWT tokens, is that the right idea?ScottG
@Laz Ziya, where should I put this dictionary? I need to access it from a controller and I can't store in inside my Hub.ScottG
this page cold help you, it contains two samples on how to save connections; 1. In Memory 2. Database if you need to access connectons from controller, so database could be the solution.LazZiya

1 Answers

0
votes

If you are using the latest version you should be able to do it by User Id.

public async Task SendMessage(string userId, string message)
{
    await Clients.User(userId).SendAsync(message);
}

OR

await _hubContext.Clients.User(userId).SendNotificationMessage(new NotificationMessage { "some message"  });