Enable Javascript

Please enable Javascript to view website properly

Toll Free 1800 889 7020

Looking for an Expert Development Team? Take 2 weeks Free Trial! Try Now

Chat Web App with ASP.NET Core 3.1 and SignalR

Agenda

In this article, we will create an ASP.NET Core 3.1 Web app that acts like a chat application. All the connected clients will be notified when a new message comes in the queue. We will use this using the following technologies:

  • .NET Core 3.1
  • SignalR
  • ASP.NET Razor pages

We will not dive into the basics, so ASP.NET developers have prior knowledge of .NET Core application architecture is needed.

Tools:

  • Visual Studio Code
  • .NET Core 3.1 SDK

Let’s start

Step 1: Install Visual Studio Code from https://code.visualstudio.com

Chat Web App with ASP.NET

Step 2: Install .NET Core 3.1 SDK from https://dotnet.microsoft.com/download/dotnet-core/3.1.

Chat Web App with ASP.NET

Note: Download the correct installer based on the architecture of your computer.

Step 3: Create a folder at the location where you want to save the source code of your chat application. I created on my desktop.

Chat Web App with ASP.NET

Step 4: Open Visual Studio Code and open this folder.

Chat Web App with ASP.NET

Step 5: Open Integrated terminal.

Chat Web App with ASP.NET

Step 6: We will be using .NET Core CLI to create the new web application and install the required libraries. So, let’s first develop a Asp.NET Core Web application and copy the below command to the terminal and press Enter.

dotnet new webapp -o realtimeChatApp
Chat Web App with ASP.NET

Step 7: Now, hit the following command to move your terminal active directory to the project directory

cd realtimeChatApp
Chat Web App with ASP.NET

Step 8: We will use a new tool known as “Libman” or Library manager. It is a Client-side content manager tool for web apps. To learn more about it, you can follow the following article.

https://devblogs.microsoft.com/aspnet/library-manager-client-side-content-manager-for-web-apps/

Step 9: Install Libman in your project directory. Hit the following command in the terminal.

dotnet tool install -g Microsoft.Web.LibraryManager.Cli
Chat Web App with ASP.NET

Note: The above screenshot shows an error because for the purpose of this demo, I already installed this on my system. When you install on your system, this command will install this tool at the Global level.

Step 10: Install signalR library using Libman in your project directory. Please hit the below command in terminal.

libman install @microsoft/signalr@latest -p unpkg -d wwwroot/js/signalr-js --files dist/browser/signalr.js --files dist/browser/signalr.min.js
Chat Web App with ASP.NET

In the screenshot above, you can see that once I hit the command, on the left pane, a Libman.json file is created. Also, the path that I mentioned is automatically created in wwwroot folder and corresponding files are copied there. This is the flexibility that we get with Libman.

Now, we are done with all the setup. Let’s code.

Step 11: At the very first, we need to create a SignalR hub that will create a persistent connection between the client and the server.

Create a folder named “Hubs” and create a new file with name “SignalRHub.cs”. Replace the code with the following code in the file.

using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace realtimeChatApp.Hubs { public class SignalRHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("BroadcastMessage", user, message); } } }

In the above code, we are inheriting from “Hub” class which is a part of .NET Core SignalR library. This will make persistent connections.

Final Code should look like this with the same folder structure as shown.

Step 12: Since we have created the Hub, we need to refer this hub in the Startup.cs file so that when the application runs, it starts the SignalR connection to this hub and our client code can subscribe to it.

Open Startup.cs file and make the following highlighted changes.

Chat Web App with ASP.NET

Now, we have successfully configured the server code. We need a client page, that can send and receive messages from this Hub. We will achieve this with the signalR.js library that we installed with Libman.

Step 13: We will create a UI screen where user can enter his name, enter the message and click a send button.

Go to Pages -> Index.cshtml and replace the code with the following code.

@page <div class="container"> <div class="row">&nbsp;&nbsp;</div> <div class="row"> <div class="col-2">User Name: </div> <div class="col-4"><input type="text" id="userName" /></div> </div> <div class="row"> <div class="col-2">Message</div> <div class="col-4"><input type="text" id="message" /></div> </div> <div class="row">&nbsp;&nbsp;</div> <div class="row"> <div class="col-6"> <input type="button" id="btnSend" value="Send" /> </div> </div> </div> <div class="row"> <div class="col-12"> <hr /> <hr /> </div> </div> <div class="row"> <div class="col-6"> <ul id="listMessage"></ul> </div> </div>
Chat Web App with ASP.NET

As you can see in the screenshot below, we are referencing two JS files. Once is the Signalr.js file that we installed with Libman and other is Chat.js.

Chat.js is that file where we will write our Javascript code that will connect to the Hub to send and receive messages with persistent connection.

Chat Web App with ASP.NET

Step 14: Now, create a file with name “chat.js” in the js folder in wwwroot and replace with the following code.

"use strict"; // Creating a connection to SignalR Hub var connection = new signalR.HubConnectionBuilder().withUrl("/signalr-hub").build(); // Starting the connection with server connection.start().then(function() {}).catch(function(err) { return console.error(err.toString()); }); // Sending the message from Client document.getElementById("btnSend").addEventListener("click", function(event) { var username = document.getElementById("userName").value; var message = document.getElementById("message").value; connection.invoke("SendMessage", username, message).catch(function(err) { return console.error(err.toString()); }); event.preventDefault(); }); // Subscribing to the messages broadcasted by Hub every time when a new message is pushed to it connection.on("BroadcastMessage", function(user, message) { var finalMessage = message.replace(/&/g, "&amp;").replace(/</g, "&lt;" ).replace( />/g, "&gt;"); var displayMsg = user + " : " + finalMessage; var li = document.createElement("li"); li.textContent = displayMsg; document.getElementById("listMessage").appendChild(li); });

Last Step: Run the application with the following command.

dotnet watch run -p realtimeChatApp.csproj

Chat Web App with ASP.NET

Now, Go to your browser and run http://localhost:5000. You will be able to see the UI page that we created. Below is the output.

Chat Web App with ASP.NET

If you notice above, we have two clients that are connecting to same hub. When one client sends the message, it is broadcasted to all connected clients.

Chat Web App with ASP.NET

So, this is how you can create a chat web app with ASP.NET Core 3.1 and SignalR. Some companies hire ASP.NET developers to build such web apps. You can create such a chat web app by following this complete guide.

Software Development Team
Need Software Development Team?
captcha
🙌

Thank you!
We will contact soon.

Oops! Something went wrong.

Recent Blogs

Categories

NSS Note
Trusted by Global Clients