Overview
SignalR simplifies adding real‑time web functionality to applications. It abstracts WebSockets, Server‑Sent Events, and long polling into a clean API, enabling server code to push content instantly to connected clients.
Prerequisites
- ASP.NET Core 8.0 SDK
- Basic knowledge of C# and JavaScript
- Node.js (optional for frontend tooling)
Step‑by‑Step Guide
- Create a new ASP.NET Core project:
dotnet new webapp -o RealTimeChat
- Add the SignalR package:
dotnet add package Microsoft.AspNetCore.SignalR
- Define a hub:
using Microsoft.AspNetCore.SignalR; public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } }
- Register SignalR in
Program.cs
:var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapHub<ChatHub>("/chatHub"); app.MapRazorPages(); app.Run();
- Create a simple client page (
wwwroot/chat.html
):<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Chat Demo</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.0/signalr.min.js"></script> </head> <body> <input id="userInput" placeholder="Name"> <input id="messageInput" placeholder="Message"> <button id="sendBtn">Send</button> <div id="messages"></div> <script> const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .withAutomaticReconnect() .build(); connection.on("ReceiveMessage", (user, message) => { const msg = document.createElement("div"); msg.textContent = `${user}: ${message}`; document.getElementById("messages").appendChild(msg); }); connection.start().catch(err => console.error(err)); document.getElementById("sendBtn").addEventListener("click", () => { const user = document.getElementById("userInput").value; const msg = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, msg).catch(err => console.error(err)); }); </script> </body> </html>