ASP.NET Core SignalR with an Individual User Account


SignalR is the open-source Microsoft API which is used to add real-time web functionality to the ASP.NET Core web application. SignalR provides a persistent connection between the client-server. It uses remote procedure calls shortly known as RPC to call the client from the server.
In this article, I’m going to show how to implement ASP.NET Core SignalR with a simple chat application with a user identity.
Create an ASP.NET Core Web application
Step 1: Create a new project in Visual Studio 2019
Step 2. Select ASP.NET Core Web application template. In my case, I named the project SignalRCoreApp
Step 3: Click on create, in the next wizard select web application template and click on the change link under the Authentication section.
Step 4: Select the individual user account from the popup, as shown in the below figure.
Create a SignalR Hub  
Step 1: Right-click on the SignalRCoreApp project and create the Hub folder
Step 2: Add the Chat.cs file under the Hub folder
  1. public class Chat: Microsoft.AspNetCore.SignalR.Hub  
  2. {  
  3.     public async Task SendMessage(string message)  
  4.     {  
  5.         await Clients.All.SendAsync("ReceiveMessage",Context.User.Identity.Name?? "anonymous", message);  
  6.     }  
  7. }  
Context.User.Identity.Name gives the user name of the Identity based on the current user session.
Include the following namespaces:
  1. using Microsoft.AspNetCore.Authorization;  
  2. using Microsoft.AspNetCore.SignalR;  
Step 3: Open starup.cs file and let's configure the SignalR
Add the below code under the ConfigurationServices method:
  1. services.AddSignalR();    
Add the endpoints in the configure method:
  1. app.UseEndpoints(endpoints =>  
  2.            {  
  3.                endpoints.MapRazorPages();  
  4.                endpoints.MapHub<Chat>("/chat");     
  5.            });  
SignalR with JavaScript Client library
Step 1: Right-click on the project Add->Client-side Library
Step 2: The add client-side library wizard will appear, under provider section select unpkg
Step 3: Library- >enter @microsoft/signalr@latest
Step 4: Select specific files expand files->dist->browser->signalr.js, signalr.min.js
Step5: create a chat.js file under wwwroot->js folder
  1. "use strict";  
  3. var connection = new signalR.HubConnectionBuilder().withUrl("/Chat").build();  
  5. //Disable send button until connection is established  
  6. document.getElementById("sendBtn").disabled = true;  
  8. connection.on("ReceiveMessage"function (user, message) {  
  9.     var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");  
  10.     var encodedMsg = user + " says " + msg;  
  11.     var li = document.createElement("li");  
  12.     li.textContent = encodedMsg;  
  13.     document.getElementById("ulmessages").appendChild(li);  
  14. });  
  16. connection.start().then(function () {  
  17.     document.getElementById("sendBtn").disabled = false;  
  18. }).catch(function (err) {  
  19.     return console.error(err.toString());  
  20. });  
  22. document.getElementById("sendBtn").addEventListener("click"function (event) {      
  23.     var message = document.getElementById("txtmessage").value;  
  24.     connection.invoke("SendMessage", message).catch(function (err) {  
  25.         return console.error(err.toString());  
  26.     });  
  27.     event.preventDefault();  
  28. });  
Step 6: Open index.cshtml page and add the below code
  1. @page  
  2. <div class="container">  
  4.     <div class="row">  
  5.         <div class="col-2">Message</div>  
  6.         <div class="col-4"><input type="text" id="txtmessage" /></div>  
  7.     </div>  
  8.     <div class="row"> </div>  
  9.     <div class="row">  
  10.         <div class="col-6">  
  11.             <input type="button" id="sendBtn" value="Send" />  
  12.         </div>  
  13.     </div>  
  14. </div>  
  15. <div class="row">  
  16.     <div class="col-12">  
  17.         <hr />  
  18.     </div>  
  19. </div>  
  20. <div class="row">  
  21.     <div class="col-6">  
  22.         <ul id="ulmessages"></ul>  
  23.     </div>  
  24. </div>  
  25. <script src="~/lib/@@microsoft/signalr/dist/browser/signalr.js"></script>  
  26. <script src="~/js/chat.js"></script>  
Run the application
I logged in as in Chrome and with the same app running in Firefox along with the user session
Case 1: When user 1 – sends a message:
The above figure shows the message which is sent by in the firefox browser where the app is running with the user ( session. 
Case 2: When user 2 – sends a message:
The above figure shows the message which is sent by in the chrome browser where the app is running with the user ( session.
Source code- Github 


We have seen how to implement ASP.NET Core SignalR with an individual user account. I hope you have enjoyed this article. Your valuable feedback, questions, or comments about this article are always welcome.
Happy Coding!