Real-time .NET Chat Application: Step-by-Step Tutorial

In this tutorial, you will learn how to create a real-time chat application using .NET and SignalR. SignalR is a library that simplifies the process of adding real-time web functionality to applications.

Prerequisites

  • Visual Studio 2019 or later
  • .NET Core 3.1 or later
  • Basic knowledge of C# and ASP.NET Core

Step 1: Create a new ASP.NET Core Web Application

  1. Open Visual Studio and create a new project.
  2. Choose ASP.NET Core Web Application and click Next.
  3. Name the project "ChatApp" and click Create.
  4. Select Web Application (Model-View-Controller) and ensure that Enable Razor Runtime Compilation is checked. Click Create.

Step 2: Install the SignalR package

  1. Right-click on the project in the Solution Explorer and select Manage NuGet Packages.
  2. Click on the Browse tab, search for "Microsoft.AspNetCore.SignalR" and install the package.

Step 3: Add SignalR to Startup.cs

  1. In the Startup.cs file, add the following line in the ConfigureServices method:
services.AddSignalR();
  1. In the Configure method, add the following line before app.UseEndpoints:
app.UseSignalR(routes => routes.MapHub<ChatHub>("/chathub"));
  1. Add the required using statement at the top of the file:
using Microsoft.AspNetCore.SignalR;

Step 4: Create the ChatHub class

  1. Create a new folder called "Hubs" in the project.
  2. Inside the "Hubs" folder, create a new C# class called "ChatHub" and add the following code:
using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
  1. Add the required using statement at the top of the file:
using System.Threading.Tasks;

Step 5: Add SignalR to the View

  1. Open the _Layout.cshtml file in the "Views/Shared" folder.
  2. Add the following script reference in the head section:
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.10/signalr.min.js"></script>

Step 6: Create the Chat View

  1. In the "Views/Home" folder, create a new View called "Chat.cshtml" and add the following code:
<div class="container">
    <div class="row">&nbsp;</div>
    <div class="row">
        <div class="col-2">User:</div>
        <div class="col-4"><input type="text" id="userInput" /></div>
    </div>
    <div class="row">
        <div class="col-2">Message:</div>
        <div class="col-4"><input type="text" id="messageInput" /></div>
    </div>
    <div class="row">
        <div class="col-6">
            <button id="sendButton">Send</button>
        </div>
    </div>
    <div class="row">
        <div class="col-6">
            <ul id="messagesList"></ul>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        var connection = new signalR.HubConnectionBuilder().withUrl("/chathub").build();

        document.getElementById("sendButton").addEventListener("click", function (event) {
            var user = document.getElementById("userInput").value;
            var message = document.getElementById("messageInput").value;
            connection.invoke("SendMessage", user, message).catch(function (err) {
                return console.error(err.toString());
            });
            event.preventDefault();
        });

        connection.on("ReceiveMessage", function (user, message) {
            var li = document.createElement("li");
            li.textContent = user + " says " + message;
            document.getElementById("messagesList").appendChild(li);
        });

        connection.start().catch(function (err) {
            return console.error(err.toString());
        });
    </script>
}
  1. In the HomeController.cs, add the following action method:
public IActionResult Chat()
{
    return View();
}
  1. In the Views/Shared/_Layout.cshtml file, add a new navigation item for Chat:
<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Chat">Chat</a>
</li>

Now you can run the application and navigate to the "Chat" page to test the real-time chat functionality. Happy coding!

An AI coworker, not just a copilot

View VelocityAI