Send a message to a specific user’s connection instead of broadcasting to all clients.
Here’s a step-by-step guide:
1. Setup SignalR Hub
public class ChatHub : Hub
{
// Static dictionary to keep track of userId and connectionId
private static readonly Dictionary<string, string> _userConnections = new();
// Called when a client connects
public override Task OnConnectedAsync()
{
var userId = Context.UserIdentifier; // Must be set by authentication middleware
if (!string.IsNullOrEmpty(userId))
{
lock (_userConnections)
{
_userConnections[userId] = Context.ConnectionId;
}
}
return base.OnConnectedAsync();
}
// Called when a client disconnects
public override Task OnDisconnectedAsync(Exception exception)
{
var userId = Context.UserIdentifier;
if (!string.IsNullOrEmpty(userId))
{
lock (_userConnections)
{
_userConnections.Remove(userId);
}
}
return base.OnDisconnectedAsync(exception);
}
// Private messaging method
public async Task SendPrivateMessage(string recipientUserId, string message)
{
if (_userConnections.TryGetValue(recipientUserId, out string connectionId))
{
await Clients.Client(connectionId).SendAsync("ReceivePrivateMessage", Context.UserIdentifier, message);
}
}
}
2. Configure Authentication Middleware
Ensure that UserIdentifier is set — typically the username or user ID from your authentication system.
If you're not using full authentication, override UserIdentifier manually:
public class CustomUserIdProvider : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
// Use connection.User.Identity.Name or a query string, etc.
return connection.User?.Identity?.Name;
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Here’s a step-by-step guide:
1. Setup SignalR Hub
2. Configure Authentication Middleware
Ensure that
UserIdentifieris set — typically the username or user ID from your authentication system.In
Startup.cs(for .NET Core):If you're not using full authentication, override
UserIdentifiermanually:Register it:
3. Client-Side JavaScript Example
Tips
_userConnections) for scalability.ConcurrentDictionary<string, HashSet<string>>.Groups.AddToGroupAsync(connectionId, groupName).