question

6666666 avatar image
0 Votes"
6666666 asked ZhiLv-MSFT edited

what is the user in `Clients.User(user)` in signalr?

Clients.User(user).SendAsync()

what is the user? user id or user name?

dotnet-aspnet-core-general
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered ZhiLv-MSFT edited

Hi @6666666,

Clients.User(user).SendAsync() what is the user? user id or user name?

The user should be the user id, check the definition:

133435-image.png

You can refer the following sample, use Asp.net Core Identity to manage user and do the login action.

Code in the Chat hub:

MyChatHub.cs:

 namespace SignalRApp.Hubs
 {
     [Authorize]
     public class MyChatHub : Hub
     {
         //define a dictionary to store the userid.
         private static Dictionary<string, List<string>> NtoIdMappingTable = new Dictionary<string, List<string>>();
             
         public override async Task OnConnectedAsync()
         {
             var username = Context.User.Identity.Name;
             var userId = Context.UserIdentifier;
             List<string> userIds;
    
             //store the userid to the list.
             if (!NtoIdMappingTable.TryGetValue(username, out userIds))
             {
                 userIds = new List<string>();
                 userIds.Add(userId);
    
                 NtoIdMappingTable.Add(username, userIds);
             }
             else
             {
                 userIds.Add(userId);
             }
    
             await base.OnConnectedAsync(); 
         }
         public async Task SendMessageToAll(string user, string message)
         {
    
             await Clients.All.SendAsync("ReceiveMessage", user, message);
         }
    
    
         public async Task SendMessageToReceiver(string sender, string receiver, string message)
         {
    
             var userId = NtoIdMappingTable.GetValueOrDefault(receiver);
    
             if (userId.Count > 0)
             {
                 await Clients.User(userId.FirstOrDefault()).SendAsync("ReceiveMessage", sender, message);
             }
             else
             {
                 //the userid is null.
             }
    
         }
    
         public override async Task OnDisconnectedAsync(Exception exception)
         {
             var username = Context.User.Identity.Name;
             var userId = Context.UserIdentifier;
             List<string> userIds;
    
             //remove userid from the List
             if (NtoIdMappingTable.TryGetValue(username, out userIds))
             {
                 userIds.Remove(userId);
             }  
             await base.OnDisconnectedAsync(exception);
         }
     }
 }

Index.cshtml:

     <div class="container">
         <div class="row">&nbsp;</div>
         <div class="row">
             <div class="col-2">Sender</div>
             <div class="col-4"><input type="text" id="senderInput" value="@User.Identity.Name" /></div>
         </div>
         <div class="row">
             <div class="col-2">Receiver</div>
             <div class="col-4"><input type="text" id="receiverInput" /></div>
         </div>
         <div class="row">
             <div class="col-2">Message</div>
             <div class="col-4"><input type="text" id="messageInput" /></div>
         </div>
         <div class="row">&nbsp;</div>
         <div class="row">
             <div class="col-6">
                 <input type="button" id="sendButton" value="Send Message" />
             </div>
         </div>
     </div>

chat.js:

 document.getElementById("sendButton").addEventListener("click", function (event) {
    
     var user = document.getElementById("senderInput").value;
     var message = document.getElementById("messageInput").value;
     var receiver = document.getElementById("receiverInput").value;
     if (receiver.length > 0) {
         //if the receiver is not empty, send private message to the receiver.
         connection.invoke("SendMessageToReceiver", user, receiver, message).catch(function (err) {
             return console.error(err.toString());
         });
     }
     else { 
         //send message to all user.
         connection.invoke("SendMessageToAll", user, message).catch(function (err) {
             return console.error(err.toString());
         });
     }
    
     event.preventDefault();
 });

The result as below:

133519-capture2.png


If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Best regards,
Dillion


image.png (40.9 KiB)
capture2.png (99.6 KiB)
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

what the Context.UserIdentifier will be?

in your example it is the User Sender Input ? int the first image the Context.Identifier will be aa@hotmail.com?

means it is all write by the user? I can post a guid value to it?

0 Votes 0 ·

Hi @6666666,

The Context.UserIdentifier is the user's identifier, instead of the username, you can check this screenshot:

134100-1.gif

Since we store the username and its identifier in the dictionary, when we send messages to special user, we need to find the user's identifier based on its username, then send message.

0 Votes 0 ·
1.gif (320.5 KiB)

I want to ask that The User Identifier is auto generated or user set?

0 Votes 0 ·
Show more comments
BruceBarker-8516 avatar image
0 Votes"
BruceBarker-8516 answered
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.