DEV Community

Cover image for Build a Real-Time Chat Room with .NET Core & SignalR
Morteza Jangjoo
Morteza Jangjoo

Posted on

Build a Real-Time Chat Room with .NET Core & SignalR

Adding real-time communication to your web apps is easier than you think with SignalR. In this quick guide, we’ll build a chat room using ASP.NET Core 8 and SignalR.


Prerequisites

  • .NET 8 SDK
  • Basic C# knowledge
  • A code editor (VS Code / Visual Studio)

Create Project

dotnet new webapp -n ChatRoomApp
cd ChatRoomApp
dotnet add package Microsoft.AspNetCore.SignalR
Enter fullscreen mode Exit fullscreen mode

Create a Hub

Hubs/ChatHub.cs

using Microsoft.AspNetCore.SignalR;

namespace ChatRoomApp.Hubs;

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
Enter fullscreen mode Exit fullscreen mode

Configure SignalR

Program.cs

using ChatRoomApp.Hubs;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();

var app = builder.Build();
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapHub<ChatHub>("/chathub");
app.Run();
Enter fullscreen mode Exit fullscreen mode

Build the Client

wwwroot/index.html

<!DOCTYPE html>
<html>
<head>
  <title>Chat Room</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.0/signalr.min.js"></script>
</head>
<body>
  <h2>Chat Room</h2>
  <input id="userInput" placeholder="Name" />
  <input id="messageInput" placeholder="Message" />
  <button onclick="sendMessage()">Send</button>
  <ul id="messagesList"></ul>

  <script>
    const connection = new signalR.HubConnectionBuilder()
      .withUrl("/chathub").build();

    connection.on("ReceiveMessage", (user, msg) => {
      const li = document.createElement("li");
      li.textContent = `${user}: ${msg}`;
      document.getElementById("messagesList").appendChild(li);
    });

    connection.start();

    function sendMessage() {
      const user = userInput.value;
      const msg = messageInput.value;
      connection.invoke("SendMessage", user, msg);
    }
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Run

dotnet run
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:5000, open two tabs, and chat in real-time.


Next Steps

  • Add authentication
  • Store chat history in a database
  • Deploy to Azure / Docker

With just a few lines of code, you now have a working real-time chat room in .NET 8.


get source code from github

I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”

Top comments (0)