In the latest version of Asp.Net SignalR, was added a new way of sending a message to a specific user, using the interface "IUserIdProvider".
public interface IUserIdProvider
{
string GetUserId(IRequest request);
}
public class MyHub : Hub
{
public void Send(string userId, string message)
{
Clients.User(userId).send(message);
}
}
My question is: How do I know to whom I am sending my message? The explanation of this new method is very superficial. And the draft Statement of SignalR 2.0.0 with this bug and does not compile. Has anyone implemented this feature?
More Info : http://www.asp.net/signalr/overview/signalr-20/hubs-api/mapping-users-to-connections#IUserIdProvider
Hugs.
Best Answer
SignalR provides ConnectionId for each connection. To find which connection belongs to whom (the user), we need to create a mapping between the connection and the user. This depends on how you identify a user in your application.
In SignalR 2.0, this is done by using the inbuilt
IPrincipal.Identity.Name
, which is the logged in user identifier as set during the ASP.NET authentication.However, you may need to map the connection with the user using a different identifier instead of using the Identity.Name. For this purpose this new provider can be used with your custom implementation for mapping user with the connection.
Example of Mapping SignalR Users to Connections using IUserIdProvider
Lets assume our application uses a
userId
to identify each user. Now, we need to send message to a specific user. We haveuserId
andmessage
, but SignalR must also know the mapping between our userId and the connection.To achieve this, first we need to create a new class which implements
IUserIdProvider
:The second step is to tell SignalR to use our
CustomUserIdProvider
instead of the default implementation. This can be done in the Startup.cs while initializing the hub configuration:Now, you can send message to a specific user using his
userId
as mentioned in the documentation, like:Hope this helps.