MSDN Documentation

Introduction to ASP.NET Core SignalR

ASP.NET Core SignalR is a library for ASP.NET Core developers to simplify the process of adding real-time web functionality to applications. Real-time web functionality enables server-side code to push content to connected clients instantly as it becomes available. This is typically done using WebSockets, but SignalR also supports other fallback mechanisms like Server-Sent Events (SSE) and Long Polling when WebSockets are not available.

Key Features of SignalR

  • Real-time Communication: Push data from server to client without client polling.
  • Cross-Platform Support: Works with various clients including browsers, mobile apps, and desktop applications.
  • Scalability: Designed to handle a large number of concurrent connections.
  • Abstraction: Handles connection management and message routing, allowing developers to focus on application logic.
  • Flexible Transport: Automatically negotiates the best available transport (WebSockets, SSE, Long Polling).

Getting Started with SignalR

To get started with SignalR in your ASP.NET Core project, you need to install the appropriate NuGet packages and configure your application.

Install NuGet Packages:

For server-side:

dotnet add package Microsoft.AspNetCore.SignalR

For client-side (JavaScript):

npm install @microsoft/signalr

Configure SignalR in Startup:

In your

Startup.cs
file, configure SignalR services and endpoints.


    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
        // ... other services
    }

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

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<YourHubClass>("/yourhub"); // Register your SignalR hub
            // ... other endpoints
        });
        // ... other middleware
    }
                    

Create a SignalR Hub:

A hub is a high-level abstraction used to build real-time, bi-directional communication functionalities. It's a .NET class that inherits from

Hub
.


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

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

Client-Side Implementation (JavaScript)

Connecting to a SignalR hub from a JavaScript client is straightforward.


    import * as signalR from '@microsoft/signalr';

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

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

    connection.start().then(() => {
        console.log('SignalR Connected!');
    }).catch(err => console.error('SignalR Connection Error: ', err));

    async function sendMessageToHub(user, message) {
        try {
            await connection.invoke("SendMessage", user, message);
        } catch(err) {
            console.error('Error invoking SendMessage: ', err);
        }
    }