How to use SignalR in ASP.NET Core

By FoxLearn 1/4/2025 4:06:11 AM   44
SignalR for ASP.Net Core is an updated library that enables real-time communication in ASP.NET Core applications, allowing the server to push updates to connected clients immediately without the clients needing to request them.

SignalR for ASP.Net Core removes some features from the previous version, such as automatic reconnects and support for multiple hubs per connection, but is more robust and user-friendly. It is not compatible with the earlier version, and the new client is built with TypeScript.

Create an ASP.NET Core project and install SignalR

To get started, create a new ASP.Net Core project in Visual Studio.

  1. In Visual Studio, go to File > New > Project.
  2. From the list of templates, select ASP.Net Core Web Application (.NET Core).
  3. Name your project and click OK to create it.
  4. In the New .NET Core Web Application window, choose the Web API template.
  5. Make sure Enable Docker Support is unchecked and No Authentication is selected, as you won’t need these features for this tutorial.
  6. Click OK to create your project.

Next, install SignalR in your ASP.Net Core project.

You can do this by adding the Microsoft.AspNet.SignalR package through the NuGet Package Manager UI in Visual Studio or by running the following command in the NuGet Package Manager Console.

Install-Package Microsoft.AspNet.SignalR

Use SignalR to broadcast messages to connected clients

Let's begin by creating an ASP.Net Core web application that uses SignalR to broadcast messages to all connected clients. To do this, we'll define a custom MessageHub class that extends the Hub class from the SignalR library. The MessageHub class will include a single method, Send, which will be used to send a text message to all connected clients.

public class MessageHub : Hub
{
    public void Send(string title, string author)
    {
        // Broadcast the message to all connected clients.
        Clients.All.InvokeAsync("broadcast", title, author);
    }
}

In this implementation, the Send method will trigger a broadcast event, sending the title and author parameters to every connected client.

Configure SignalR for ASP.NET Core

The next step is to make the SignalR service available to connected clients. To do this, we need to call the AddSignalR method within the ConfigureServices method in the Startup.cs file, as shown below:

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

To enable serving static files, we should use the UseFileServer method in the Configure method.

app.UseFileServer();

Next, to map our MessageHub class, we need to add the following code in the Configure method:

app.UseSignalR(routes =>
{
    routes.MapHub<MessageHub>("/messages");
});

Here’s the complete Startup class for reference:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseFileServer();
        app.UseSignalR(routes =>
        {
            routes.MapHub<MessageHub>("/messages");
        });
    }
}

Creating a SignalR Client to Consume Real-Time Messages

The client for our real-time ASP.Net Core application can be anything a simple HTML page, a Windows app, a WPF application, or even a console app that consumes the messages sent by the server.

We will create a .NET Core Console application to consume the messages.

  1. In Visual Studio, go to File > New > Project.
  2. In the New Project window, select .NET Core from the project templates.
  3. Choose Console App (.NET Core) as the template.
  4. Specify a name and location for your project.
  5. Click OK.

This creates a new .NET Core Console application.

Next, open the project in Solution Explorer, and use the NuGet Package Manager to add the Microsoft.AspNet.SignalR.Client package.

class Program
{
    private static HubConnection hubConnection;

    static void Main(string[] args)
    {
        hubConnection = new HubConnectionBuilder()
            .WithUrl("http://localhost:50001/messages")
            .Build();

        hubConnection.StartAsync().Wait();

        var messageHub = hubConnection.CreateHubProxy("MessageHub");

        messageHub.On<string, string>("broadcast", (title, author) =>
        {
            Console.WriteLine($"{title} posted by: {author}");
        });

        Console.ReadLine();
    }
}

SignalR for ASP.Net Core is a complete rewrite of the original SignalR library, designed to send push notifications from the server to connected clients. If you've used the older version of SignalR, you'll find this new version simpler and more user-friendly.