How to use SignalR in ASP.Net Core

Take advantage of SignalR to add real-time web functionality to your ASP.Net Core applications

How to use SignalR in ASP.Net Core
Thinkstock

SignalR for ASP.Net Core is a new version of the SignalR library that enables you to implement real-time communications in ASP.Net Core applications. Here the term “real-time” means that the server application can push data or content to connected clients as soon as updates happen, without clients having to request them. You can learn more about SignalR from my earlier post on SignalR for ASP.Net.

Note that SignalR for ASP.Net Core drops some of the features found in SignalR for ASP.Net (including automatic reconnects, support for progress messages, multiple hubs per connection) but is more robust and easier to use. As a result, this new version is not compatible with its predecessor. Note too that the new SignalR client is based on TypeScript. 

In this article we’ll look at how we can work with SignalR in ASP.Net Core. We’ll create a simple server that broadcasts text messages to clients, and a console application that consumes the messages. 

Create an ASP.Net Core project and install SignalR

First off, create a new ASP.Net Core project in Visual Studio. Assuming that you’re running Visual Studio Community Edition 2017 and .Net Core is already installed in your system, follow these steps to create an ASP.Net Core application.

  1. In Visual Studio, click on File > New > Project.
  2. Select “ASP.Net Core Web Application (.Net Core)” from the list of the templates displayed.
  3. Specify a name for the project and click OK to save it.
  4. In the “New .Net Core Web Application…” window, select “Web API.”
  5. Ensure that “Enable Docker Support” is unchecked and that “No Authentication” is selected as we won’t be using either here.
  6. Click OK.

Now install SignalR in your ASP.Net Core project. You can do this by installing the Microsoft.AspNet.SignalR package via the NuGet Package Manager UI from within Visual Studio, or by entering the command below in the NuGet Package Manager Console window. As of this writing, the latest stable version of this package is 2.2.3.

Install-Package Microsoft.AspNet.SignalR

Use SignalR to broadcast messages to connected clients

Let’s start by implementing an ASP.Net Core web application that leverages SignalR to broadcast messages to all connected clients. To achieve this, let’s create our own MessageHub class that will extend the Hub class of the SignalR library. Our MessageHub class will have just one method called Send that we will use to send a text message to all connected clients.

Here is the MessageHub class. Note that it extends the Hub class.

public class MessageHub : Hub
    {
        public void Send(string title, string author)
        {
         // Call the broadcast method to update all connected clients.
            Clients.All.InvokeAsync(“broadcast”, title, author);
        }
    }

Configure SignalR for ASP.Net Core

The next step is to expose the SignalR service so that it can be consumed by connected clients. To do this, we will make a call to the AddSignalR method in the ConfigureServices method of the Startup.cs file as shown in the code snippet below.

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

To be able to serve static files, we must use the following method in the Configure method. Incidentally, the Configure method is called automatically by the runtime.

app.UseFileServer();

To be able to map the MessageHub we just created, we need to specify the following code in the Configure method.

app.UseSignalR(routes =>
            {
                routes.MapHub<MessageHub>(“messages”);
            });

Here is the complete code listing of the Startup class for your 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”);
            });
        }
    }

Create 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 application, a Windows Presentation Foundation application, or even a console application that can consume the messages sent by the server. Let’s now create a .Net Core Console application to consume the messages. To do this, follow the steps outlined below.

  1. In the Visual Studio IDE, click on File > New > Project.
  2. In the “New Project” window that is shown next, select “.Net Core” from the list of the installed project groups.
  3. Select “Console App (.Net Core)” as the template.
  4. Specify a name and location for your project.
  5. Click OK.

This will create a .Net Core Console application project. Next, select the project in the Solution Explorer window and add the Microsoft.AspNet.SignalR.Client package via the NuGet Package Manager.

The following code listing illustrates how the messages posted by the server can be consumed by our console client.

class Program
    {
        private static HubConnection hubConnection;
        static void Main(string[] args)
        {
            hubConnection = new HubConnection(“http://localhost:50075/messages”);          
            hubConnection.Start();
            var messageHub = hubConnection.CreateHubProxy(“MessageHub”);
            messageHub.On<string, string>(“broadcast”, (article, author) =>
            {
                Console.WriteLine($”{article} posted by: {author}”);
            });
            Console.ReadLine();
        }
     }

SignalR for ASP.Net Core is a rewrite of SignalR for ASP.Net that can be used to send push notifications from the server to connected clients. If you worked with the original SignalR in the past, you will find this new version for ASP.Net Core to be simpler and easier to use. However, some features have been dropped, which means you cannot use the old server with new clients or vice versa.

Copyright © 2018 IDG Communications, Inc.