Getting Started with ASP.NET Core SignalR

This guide will walk you through the essential steps to set up and start using ASP.NET Core SignalR in your applications. SignalR enables real-time web functionality, allowing server-side code to push content to connected clients instantly.

1. Prerequisites

Before you begin, ensure you have the following installed:

2. Creating a New ASP.NET Core Project

You can create a new ASP.NET Core project using the .NET CLI or your preferred IDE. For example, to create a new empty web application:

dotnet new webapp -n MySignalRApp
cd MySignalRApp

3. Adding SignalR to Your Project

SignalR is included by default in recent ASP.NET Core templates. If you're using an older template or a custom one, you might need to add the SignalR NuGet package:

dotnet add package Microsoft.AspNetCore.SignalR

4. Configuring SignalR Services

In your Program.cs file (or Startup.cs in older versions), configure SignalR services and endpoints. This involves adding SignalR to the dependency injection container and mapping the SignalR hub endpoint.

For .NET 6 and later (using Minimal APIs):

// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSignalR(); // Add SignalR services

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapRazorPages();
app.MapHub<ChatHub>("/chat"); // Map the SignalR hub endpoint

app.Run();

For .NET 5 and earlier (using Startup.cs):

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddSignalR(); // Add SignalR services
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other middleware

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapHub<ChatHub>("/chat"); // Map the SignalR hub endpoint
    });
}

5. Creating a SignalR Hub

A SignalR hub is a pipeline that allows clients to send messages to the server and receive messages from the server. Create a new C# class that inherits from Hub.

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

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

In this example, the SendMessage method is a server-side method that clients can call. When called, it broadcasts a message to all connected clients with the ReceiveMessage method.

6. Implementing the Client-Side JavaScript

You'll need to add client-side JavaScript to connect to the SignalR hub, send messages, and receive messages.

First, ensure you have the SignalR JavaScript client library included in your project. You can use a CDN or install it via npm.

Using a CDN (in your _Layout.cshtml or similar):

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

Example JavaScript in a Razor Page or HTML file:

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chat") // The endpoint mapped in Program.cs/Startup.cs
    .withAutomaticReconnect()
    .build();

connection.on("ReceiveMessage", (user, message) => {
    // Logic to display the received message
    console.log(`Message from ${user}: ${message}`);
    const msg = message.replace(/&/g, "&").replace(/\/g, ">");
    const encodedMsg = `${user} says ${msg}`;
    const li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(() => {
    console.log("SignalR Connected!");
    // You can optionally enable sending messages once connected
    // document.getElementById("sendButton").disabled = false;
}).catch(err => console.error(err.toString()));

// Example function to send a message (called from a button click)
function sendMessage() {
    const user = document.getElementById("userInput").value;
    const message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
}

// Example of how to wire up sendMessage to a button:
// document.getElementById("sendButton").addEventListener("click", sendMessage);

7. Next Steps

Congratulations! You've successfully set up a basic SignalR application. You can now explore more advanced features like:

For more in-depth information, refer to the official SignalR documentation.

Explore Hubs