ASP.NET Core 2.0 And SignalR Core (Alpha)

In this article, we will learn how to use SignalR Core in ASP.NET Core 2.0 web applications to provide real-time communication.

Scenario

After processing a payroll, the system will trigger a report generation process. Once this process is complete, we want to notify all the web clients that their reports are available to view.

Note

I want to demonstrate a real world usage of SignalR but also want to keep it simple enough. Like SignalR, this post is ‘alpha’ too, i.e., be gentle in your feedback if you find bugs 

NoteI am assuming that you are familiar with the previous version of SignalR. If not, please check the documentation here.

Solution

We will build two applications: Server and Client. The server will receive notifications from the reporting engine when reports are ready and in-turn, it will notify the clients.

Server

Create an empty console application (.NET Core) and add NuGet packages.

  • AspNetCore.All
  • AspNetCore.SignalR

Update the Program class.

  1. public class Program  
  2.     {  
  3.         public static void Main(string[] args)  
  4.         {  
  5.             BuildWebHost(args).Run();  
  6.         }  
  7.    
  8.         public static IWebHost BuildWebHost(string[] args) =>  
  9.             WebHost.CreateDefaultBuilder(args)  
  10.                 .UseStartup<Startup>()  
  11.                 .Build();  
  12.     } 

Add a Startup class to add services and middleware for SignalR.

  1. public class Startup  
  2.     {  
  3.         public void ConfigureServices(  
  4.             IServiceCollection services)  
  5.         {  
  6.             services.AddCors(options =>  
  7.             {  
  8.                 options.AddPolicy("fiver",  
  9.                     policy => policy.AllowAnyOrigin()  
  10.                                     .AllowAnyHeader()  
  11.                                     .AllowAnyMethod());  
  12.             });  
  13.    
  14.             services.AddSignalR(); // <-- SignalR  
  15.         }  
  16.    
  17.         public void Configure(  
  18.             IApplicationBuilder app,   
  19.             IHostingEnvironment env)  
  20.         {  
  21.             app.UseCors("fiver");  
  22.    
  23.             app.UseSignalR(routes =>  // <-- SignalR  
  24.             {  
  25.                 routes.MapHub<ReportsPublisher>("reportsPublisher");  
  26.             });  
  27.         }  
  28.     }  

Create a class that inherits from SignalR Hub class.

  1. public class ReportsPublisher : Hub  
  2.     {  
  3.         public Task PublishReport(string reportName)  
  4.         {  
  5.             return Clients.All.InvokeAsync("OnReportPublished", reportName);  
  6.         }  
  7.     }  

Client

Create an empty ASP.NET Core 2.0 web application and add NuGet package Microsoft.AspNetCore.SignalR. Update the Startup class to add services and middleware for MVC.

  1. public class Startup  
  2.     {  
  3.         public void ConfigureServices(  
  4.             IServiceCollection services)  
  5.         {  
  6.             services.AddMvc();  
  7.         }  
  8.    
  9.         public void Configure(  
  10.             IApplicationBuilder app,   
  11.             IHostingEnvironment env)  
  12.         {  
  13.             app.UseStaticFiles();  
  14.             app.UseMvcWithDefaultRoute();  
  15.         }  
  16.     }  

Add three Controllers (Home, Publisher, Reports), each returning Index View, e.g.,

  1. public class HomeController : Controller  
  2.     {  
  3.         public IActionResult Index() => View();  
  4.     }  

Note Download the JavaScript files for SignalR and copy in wwwroot/js folder. You can find these in the source code for the project that accompanies this post.

Add a Layout View.

  1. <!DOCTYPE html>  
  2.    
  3. <html>  
  4. <head>  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <title>ASP.NET Core SignalR</title>  
  7.    
  8.     <script src="js/signalr-client.min.js"></script>  
  9.     <script src="js/jquery.min.js"></script>  
  10. </head>  
  11. <body>  
  12.     <div>  
  13.         @RenderBody()  
  14.         @RenderSection("scripts", required: false)  
  15.     </div>  
  16. </body>  
  17. </html>  

Add Index View for Publisher Controller.

  1. <h2>Publisher</h2>  
  2.    
  3. <input type="text" id="reportName" placeholder="Enter report name" />  
  4. <input type="button" id="publishReport" value="Publish" />  
  5.    
  6. @section scripts {  
  7.     <script>  
  8.         $(function () {  
  9.    
  10.             let hubUrl = 'http://localhost:5000/reportsPublisher';  
  11.             let httpConnection = new signalR.HttpConnection(hubUrl);  
  12.             let hubConnection = new signalR.HubConnection(httpConnection);  
  13.    
  14.             $("#publishReport").click(function () {  
  15.                 hubConnection.invoke('PublishReport', $('#reportName').val());  
  16.             });  
  17.    
  18.             hubConnection.start();  
  19.    
  20.         });  
  21.     </script>  
  22. }  

Add Index View for Reports Controller.

  1. <h2>Reports</h2>  
  2.    
  3. <ul id="reports"></ul>  
  4.    
  5. @section scripts {  
  6.     <script>  
  7.         $(function () {  
  8.    
  9.             let hubUrl = 'http://localhost:5000/reportsPublisher';  
  10.             let httpConnection = new signalR.HttpConnection(hubUrl);  
  11.             let hubConnection = new signalR.HubConnection(httpConnection);  
  12.               
  13.             hubConnection.on('OnReportPublished', data => {  
  14.                 $('#reports').append($('<li>').text(data));  
  15.             });  
  16.    
  17.             hubConnection.start();  
  18.    
  19.         });  
  20.     </script>  
  21. }  

Run both the Server and Client applications. You can open multiple instances of browser windows and observe the output.

ASP.NET Core 2.0

Note

Publisher Controller acts as the reporting engine that notifies the server of report completion.

Source Code

GitHub

Up Next
    Ebook Download
    View all
    Learn
    View all