ASP.NET SignalR: Real-time Web Functionality

Build real-time web applications with ASP.NET SignalR.

ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of building real-time web functionality that is exposed over the WebSocket protocol and then gracefully degrades to other techniques like Server-Sent Events (SSE) and long polling when WebSockets are not available.

With SignalR, you can push content from the server to connected clients instantly, as it happens, enabling rich, interactive user experiences. This is ideal for scenarios like live chat applications, real-time dashboards, collaborative editing tools, and gaming.

Key Features

Getting Started

To get started with SignalR in your ASP.NET Core application, you'll need to install the appropriate NuGet packages and configure it in your application's startup class.

Server-side Setup (ASP.NET Core)

Install the Microsoft.AspNetCore.SignalR NuGet package.

dotnet add package Microsoft.AspNetCore.SignalR

In Program.cs (or Startup.cs for older templates):

// Add SignalR services
builder.Services.AddSignalR();

// ...

// Map the SignalR hub
app.MapHub<MyHub>("/myhub");

Define your Hub class:

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

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

Client-side Integration (JavaScript)

Include the SignalR JavaScript client library. You can use a CDN or install it via npm.

<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.min.js"></script>

Establish a connection to your hub:

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/myhub")
    .build();

connection.on("ReceiveMessage", (user, message) => {
    console.log(`Message from ${user}: ${message}`);
    // Update UI here
});

connection.start().catch(err => console.error(err.toString()));

Learn More