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

mc 4,796 Reputation points
2021-09-17T09:57:48.34+00:00

Clients.User(user).SendAsync()

what is the user? user id or user name?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,668 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,546 Reputation points Microsoft Vendor
    2021-09-20T08:03:10.31+00:00

    Hi @mc ,

    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


1 additional answer

Sort by: Most helpful
  1. Bruce Barker 801 Reputation points
    2021-09-17T14:47:23.063+00:00
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.