Build Real-time Applications with SignalR in ASP.NET Core
SignalR
SignalR is basically a library that helps us to send or receive messages at realtime . When you use signalr and application is running at multiple instances and you send any messages it gets refreshed at all instances. That we often use fir building real-time application in Asp.net.
So first of all what we will have is a asp.net core web application. We are currently using Asp.net core 6.0 for our tutorial.
Now install nuget package Microsoft.AspNetCore.SignalR.Client in your application. You can see the package in the image below
You can also use the command below
NuGet\Install-Package Microsoft.AspNetCore.SignalR.Client -Version 6.0.9
Now go to program.cs file and there we have to add SignalR to the services. You can do the same in Asp.net Core 3.1 and earlier versions than Asp.net core 6.0. In earlier version we will do that in Startup.cs file.
builder.Services.AddSignalR();Now , after addign SignalR to the services we have to add SignalR chathub endpoints. These will be the endpoint that we have to use to connect to signalr.
app.UseEndpoints(routes => { routes.MapHub<ChatHub>("/chatHub"); });
ChatHub is a class file that we have to add and inherit it as Hub as showed in the image. This is the file where you will write all the methods related to signalR.
using Microsoft.AspNetCore.SignalR; namespace SignalR { public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } } }
Now after addign the chathub file we have to go to client side and add one new js file . We will name it chat.js here we will add methods to call and receiver SignalR methods.
const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .build(); //This method receive the message and Append to our list connection.on("ReceiveMessage", (user, message) => { debugger const msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); const encodedMsg = user + " :: " + msg; const li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); }); connection.start().catch(err => console.error(err.toString())); //Send the message document.getElementById("sendMessage").addEventListener("click", event => { debugger const user = document.getElementById("userName").value; const message = document.getElementById("userMessage").value; connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString())); event.preventDefault(); });
In the html part we will add two controls for User and message data for dummy purpose and then we have to add two signalr Cdn as showed below.
@page <div class="container"> <div class="row"> </div> <div class="row"> <div class="col-md-12"> <div class="col-md-6"> <div class="col-md-3">User</div> <div class="col-md-9"><input type="text" id="userName" /></div> </div> </div> <div class="col-md-12"> <div class="col-md-6"> <div class="col-md-3">Message</div> <div class="col-md-9"> <input type="text" id="userMessage" /> <input type="button" id="sendMessage" value="Send Message" /> </div> </div> </div> </div> <div class="row"> <div class="col-12"> <hr /> </div> </div> <div class="row"> <div class="col-6"> </div> <div class="col-6"> <ul id="messagesList"></ul> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/aspnet-signalr/1.0.27/signalr.min.js" integrity="sha512-a+73ErrZPjhqOu0qbW1QLsenEF4pvDjmnd+Ws6hkDyJlrwAigOQAxQhIT+fPNFWScUvtJQvn+G535TT2C6/G4g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/aspnet-signalr/1.0.27/signalr.js" integrity="sha512-RnZfhh4QUtg97mSlY5mFfp/yqJpEUBmAUU6JI3xrOWshmw9CJB4ejsd7YTB15JmUWMHMB7s4NrqueF+zrskEtQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="~/js/chat.js"></script>
Now run the application and open the application in multiple browsers at the same time.See Output
So this is how you can Build Real-time Applications with SignalR in ASP.NET Core.