Building a Real-Time Chat Application with .NET Core 7 SignalR

Introduction

Real-time communication has become an essential aspect of modern web applications. Whether you're building a chat application, a collaborative workspace, or a real-time dashboard, you need a reliable and efficient way to send and receive messages in real time. That's where SignalR comes in.

What is SignalR in ASP.NET Core?

SignalR is a real-time communication library for ASP.NET Core. It allows you to build real-time web applications that can push messages to clients as soon as they become available. SignalR uses WebSockets as the default transport protocol, but it can also use other transport protocols, such as Server-Sent Events (SSE) and Long Polling.

This article will show you how to build a real-time chat application with .NET Core 7 and SignalR. We'll cover the following topics,

  1. Setting up the project
  2. Creating the Chat Hub
  3. Creating the Chat UI
  4. Running the application

Let's get started!

1. Setting up the project

First, let's create a new ASP.NET Core 7 project. Open up Visual Studio and select "Create a new project". Choose "ASP.NET Core Web Application" as the project type and give it a name.

Next, select "Web Application" as the project template and make sure that "Enable Docker Support" is unchecked. Click "Create" to create the project.

Once the project is created, open up the "Program.cs" file and add the following code to add SignalR,

builder.Services.AddSignalR();
builder.Services.AddControllersWithViews();

2. Creating the Chat Hub

The Chat Hub is where we'll handle all the real-time communication between the server and the client. Let's create a new class called "ChatHub" in our project's "Hubs" folder.

Add the following code to the class.

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace YourProjectName.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

We've defined a single method called "SendMessage" that takes two parameters: "user" and "message". This method sends a message to all connected clients by calling the "SendAsync" method on the "Clients" object. This code creates a new Hub class inherited from the SignalR Hub class.

Now that we've created the Chat Hub, we must configure the SignalR middleware to use it. Add the following code to the Configure method in the "Program.cs" file: Now that we've created the Chat Hub, we need to configure the SignalR middleware to use it. Add the following code to the Configure method in the "Program.cs" file,

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapHub<ChatHub>("/chatHub");

This code configures the SignalR middleware to use the Chat Hub by mapping the "/chatHub" URL to the ChatHub class.

3. Creating the Chat UI

Now that we've created the Chat Hub, we must create a UI for our chat application. This tutorial will use a simple HTML page with some JavaScript code to handle real-time communication.

In the  "index.html" file of your project, add the following code,

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Real-Time Chat with SignalR</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.13/signalr.min.js"></script>
</head>
<body>
    <div>
        <input type="text" id="username" placeholder="Enter your username" />
        <input type="text" id="message" placeholder="Enter your message" />
        <button id="sendButton">Send</button>
    </div>
    <div id="chatBox"></div>
    <script>
        var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

        connection.on("ReceiveMessage", function (user, message) {
            var encodedUser = $("<div />").text(user).html();
            var encodedMsg = $("<div />").text(message).html();
            $("#chatBox").append("<p><strong>" + encodedUser + "</strong>: " + encodedMsg + "</p>");
        });

        $("#sendButton").click(function () {
            var user = $("#username").val();
            var message = $("#message").val();
            connection.invoke("SendMessage", user, message);
            $("#message").val("").focus();
        });

        connection.start().then(function () {
            console.log("Connected!");
        }).catch(function (err) {
            console.error(err.toString());
        });
    </script>
</body>
</html>

This code creates a basic UI with an input field for the user's name, an input field for the message, and a "Send" button. It also creates a div with an id of "chatBox", where we'll display the chat messages.

In the JavaScript code, we create a new SignalR connection using the URL "/chatHub" (which we mapped to our ChatHub class in the "Startup.cs" file). We then define a function to handle the "ReceiveMessage" event, called whenever the server sends a message to the client. This function appends the message to the chatBox div.

We also define a click event handler for the "Send" button, which invokes the "SendMessage" method on the server with the user's name and message. Finally, we start the SignalR connection and log a message to the console when the connection is established.

4. Running the application

We're now ready to run the application. Press F5 to start the application in debug mode. Once the application runs, you should see the chat UI with the input fields and the "Send" button. Press F5 to start the application in debug mode. Once the application is running, you should see the chat UI with the input fields and the "Send" button. We're now ready to run the application.is ning

Enter your name and a message, and click the "Send" button. You should see your message appear in the chat box. Open up another browser window and navigate to the same URL. Enter a different name and send a message. You should see the message appear in both windows.

Congratulations, you've just built a real-time chat application with .NET Core 7 and SignalR!

Conclusion

This article shows you how to build a real-time chat application with .NET Core 7 and SignalR. We've covered the basics of setting up the project, creating the Chat Hub, and creating the Chat UI. We hope this tutorial has helped you understand the power of SignalR and how it can be used to build real-time web applications. Happy coding!