SignalR Real‑time Communication

Build interactive, real‑time web applications with ASP.NET Core SignalR.

Start Tutorial

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

Step‑by‑Step Guide

  1. Create a new ASP.NET Core project:
    dotnet new webapp -o RealTimeChat
  2. Add the SignalR package:
    dotnet add package Microsoft.AspNetCore.SignalR
  3. 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);
        }
    }
  4. Register SignalR in Program.cs:
    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();
    
    app.MapHub<ChatHub>("/chatHub");
    app.MapRazorPages();
    
    app.Run();
  5. 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>
    

Live Demo

Chat Demo

Next Steps