I'm working through the SignalR
Microsoft tutorial located here.
Everything is working ok, however, I wanted to try to change the code in ChatHub#SendMessage
to send a message to a specific user.
So I modified the code like this:
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
//await Clients.All.SendAsync("ReceiveMessage", user, message);
await Clients.User(user).SendAsync("ReceiveMessage", message);
}
}
However, the user never gets the message. The message is only sent if you use Clients.All.SendAsync
(that's the line that's commented out above).
I also did more research and found from this answer that maybe I need to implement a custom user provider. So I implemented one:
public class CustomUserIdProvider : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
return "user1";
}
}
Then in Startup.cs
, I registered this provider:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddSingleton<IUserIdProvider, CustomUserIdProvider>();
services.AddSignalR();
}
Then I tried using the Context.UserIdentifier
when sending the message, like this:
public async Task SendMessage(string user, string message)
{
//await Clients.All.SendAsync("ReceiveMessage", user, message);
await Clients.User(Context.UserIdentifier).SendAsync("ReceiveMessage", message);
}
But it still does not seem to send the message.
What am I doing wrong?