I am trying to implement a chat feature in a blazor solution (.NET 8), the chat is very simple, every user must be able to message every user in a application similar to whatsapp web, this is the Hub
public class ChatHub : Hub{ private readonly ChatService _chatService; public ChatHub(ChatService chatService) { _chatService = chatService; } public async Task SendMessage(string receiverId, string message) { var senderId = Context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; await _chatService.SaveMessageAsync(senderId, receiverId, message); await Clients.User(receiverId).SendAsync("ReceiveMessage", senderId, message); }}the problem I am having is that the line:
var senderId = Context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;is always returning null, after some research I found out that ClaimTypes.NameIdentifier in this context could not be returning null as the id it's going to return is the id I need to point to the signal R client I am trying to connect, therefore hardcoding the Identity ID or using the connection Id from Signal R also did not work
I tried setting the Identity Ids to Signal R IDs using this
public class NameIdentifierUserIdProvider : IUserIdProvider{ public string GetUserId(HubConnectionContext connection) { return connection.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; }}builder.Services.AddSingleton<IUserIdProvider, NameIdentifierUserIdProvider>();I tried hardcoding the Identity IDs in the hub for testing also without success
tried also using the signal R connection IDs directly like this
public override async Task OnConnectedAsync(){ var userId = Context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (!string.IsNullOrEmpty(userId)) { _userConnectionMap.TryAdd(userId, Context.ConnectionId); } await base.OnConnectedAsync();}public async Task SendMessage(string receiverId, string senderId, string message){ await _chatService.SaveMessageAsync(senderId, receiverId, message); if (_userConnectionMap.TryGetValue(receiverId, out string connectionId)) { await Clients.Client(connectionId).SendAsync("ReceiveMessage", senderId, message); }}