Create Group connections that are specific to a user

PHOTO EMBED

Sun Jul 02 2023 19:05:28 GMT+0000 (Coordinated Universal Time)

Saved by @cameron_v_r #signalr #c#

using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;
using System.Threading.Tasks;

public class MyHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        var userId = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
        await Groups.AddToGroupAsync(Context.ConnectionId, userId);

        await base.OnConnectedAsync();
    }
}
////////////////////////////////////////////////////////////////////
public async Task SendMessageToUser(string userId, string message)
{
    await Clients.Group(userId).SendAsync("ReceiveMessage", message);
}
content_copyCOPY

In this example, the OnConnectedAsync method is overridden to add the connection (identified by Context.ConnectionId) to a group named after the user's unique identifier. The ClaimTypes.NameIdentifier is used to retrieve the user's identifier from the claims associated with the connection's User property. By adding the connection to a group named after the user's identifier, you can later target messages or events specifically to that user by invoking methods on the group using Clients.Group(userId). In the above code, the SendMessageToUser method targets the group associated with the specified userId and invokes the ReceiveMessage method on all connections within that group. This allows you to send messages or notifications directly to a specific user. Remember to configure your authentication mechanism properly to ensure the user's unique identifier is available in the ClaimTypes.NameIdentifier claim.