Implementation Of SignalR With .NET Core

In my previous, we have seen how SignalR is useful with .NET Core. you can read the previous article from here. Now in this article, we will see the implementation of SignalR with .NET core

Introduction

In my previous article, we have seen how SignalR is useful with .NET Core. You can read the previous article from here:

 Now in this article, we will see the implementation of SignalR with .NET core

Software’s requires to develop an application with SignalR on ASP.NET Core

  • Node package manager(npm) - https://www.npmjs.com/get-npm
  • .NET Core SDK 2.1 or later -https://www.microsoft.com/net/download/archives
  • Visual Studio 2017 (Version 15.7.3 or later)

Let’s create simple communication application using SignalR with ASP.NET Core

  • File - New - Project - Create New web application.

    SignalR With .NET Core

  • Then select Web Application.

    SignalR With .NET Core

  • Next step is to download a SignalR module using a node package manager.

    • npm init -y
    • npm install @aspnet/signalr
  • Copy signalr.js file from node installed location and copy in our project.
  • Do not forget to include signalr.js file into your HTML Page script tag.

Create SignaR Hub

  • Now to create a SignalR hub, a signalR hub is a class that inherits from Microsoft.ASpNetCore.SignalR.Hub.

  • Let’s create a method that can be accessed from JavaScript.

  • To send the message to all clients, I have created “SendMessage” method and within this method, I will call the “ReceiveMessage” method of the connected client.
    1. using Microsoft.AspNetCore.SignalR;  
    2. using System.Threading.Tasks;  
    3. namespace CommunicationApp  
    4. {  
    5.     public class ChatHub : Hub  
    6.     {  
    7.         public async Task SendMessage(string user, string message)  
    8.         {  
    9.             await Clients.All.SendAsync("ReceiveMessage", user, message);  
    10.         }  
    11.     }  
    12. }  
  • Next step is that we need to configure our project to handle the SignalR Request.
  • So to configure SignalR in our project, we need to add signalR service to ConfigureService method of startup class.
    1. public void ConfigureServices(IServiceCollection services)  
    2. {  
    3.     ....  
    4.     ....  
    5.     services.AddSignalR();  
    6. }  
  • Also we need to configure the route to signalR hubs using UseSignalR method defined in configure method of startup class.

  • This method(app.UseSignalR) adds SignalR to a middleware pipeline.
    1. public void Configure(IApplicationBuilder app)  
    2. {  
    3.     ...  
    4.     ...  
    5.     app.UseSignalR(routes =>  
    6.     {  
    7.            routes.MapHub<ChatHub>("/chatHub");  
    8.      });  
    9.   
    10.      app.UseMvc();  
    11. }  
  • So by using JavaScript code, we call the server method called “SendMessage” and also we have registered ReceiveMessage method, which is usually called from the server to send the message to the client.

  • Just create chat.js file under “wwwroot/js” folder.
    1. const connection = new signalR.HubConnectionBuilder()  
    2.     .withUrl("/chatHub")  
    3.     .build();  
    4.   
    5. //This method receive the message and Append to our list  
    6. connection.on("ReceiveMessage", (user, message) => {  
    7.     const msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");  
    8.     const encodedMsg = user + " :: " + msg;  
    9.     const li = document.createElement("li");  
    10.     li.textContent = encodedMsg;  
    11.     document.getElementById("messagesList").appendChild(li);  
    12. });  
    13.   
    14. connection.start().catch(err => console.error(err.toString()));  
    15.   
    16. //Send the message  
    17.   
    18. document.getElementById("sendMessage").addEventListener("click", event => {  
    19.     const user = document.getElementById("userName").value;  
    20.     const message = document.getElementById("userMessage").value;  
    21.     connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));  
    22.     event.preventDefault();  
    23. });   
  • Now replace the following code content in page\index.cshtml file.
    1. @page  
    2. <div class="container">  
    3.     <div class="row"> </div>  
    4.     <div class="row">  
    5.         <div class="col-md-12">  
    6.             <div class="col-md-6">  
    7.                 <div class="col-md-3">User</div>  
    8.                 <div class="col-md-9"><input type="text" id="userName" /></div>  
    9.             </div>  
    10.         </div>  
    11.         <div class="col-md-12">  
    12.             <div class="col-md-6">  
    13.                 <div class="col-md-3">Message</div>  
    14.                 <div class="col-md-9">  
    15.                     <input type="text" id="userMessage" />      
    16.                     <input type="button" id="sendMessage" value="Send Message" />  
    17.                 </div>  
    18.             </div>  
    19.         </div>  
    20.     </div>  
    21.     <div class="row">  
    22.         <div class="col-12">  
    23.             <hr />  
    24.         </div>  
    25.     </div>  
    26.     <div class="row">  
    27.         <div class="col-6"> </div>  
    28.         <div class="col-6">  
    29.             <ul id="messagesList"></ul>  
    30.         </div>  
    31.     </div>  
    32. </div>  
    33. <script src="~/lib/signalr/signalr.js"></script>  
    34. <script src="~/js/chat.js"></script>  
    SignalR With .NET Core

Thanks and please share this article.