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
Note - I 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.
- public class Program
- {
- public static void Main(string[] args)
- {
- BuildWebHost(args).Run();
- }
-
- public static IWebHost BuildWebHost(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .UseStartup<Startup>()
- .Build();
- }
Add a Startup class to add services and middleware for SignalR.
- public class Startup
- {
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddCors(options =>
- {
- options.AddPolicy("fiver",
- policy => policy.AllowAnyOrigin()
- .AllowAnyHeader()
- .AllowAnyMethod());
- });
-
- services.AddSignalR();
- }
-
- public void Configure(
- IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseCors("fiver");
-
- app.UseSignalR(routes =>
- {
- routes.MapHub<ReportsPublisher>("reportsPublisher");
- });
- }
- }
Create a class that inherits from SignalR Hub class.
- public class ReportsPublisher : Hub
- {
- public Task PublishReport(string reportName)
- {
- return Clients.All.InvokeAsync("OnReportPublished", reportName);
- }
- }
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.
- public class Startup
- {
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddMvc();
- }
-
- public void Configure(
- IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseStaticFiles();
- app.UseMvcWithDefaultRoute();
- }
- }
Add three Controllers (Home, Publisher, Reports), each returning Index View, e.g.,
- public class HomeController : Controller
- {
- public IActionResult Index() => View();
- }
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.
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>ASP.NET Core SignalR</title>
-
- <script src="js/signalr-client.min.js"></script>
- <script src="js/jquery.min.js"></script>
- </head>
- <body>
- <div>
- @RenderBody()
- @RenderSection("scripts", required: false)
- </div>
- </body>
- </html>
Add Index View for Publisher Controller.
- <h2>Publisher</h2>
-
- <input type="text" id="reportName" placeholder="Enter report name" />
- <input type="button" id="publishReport" value="Publish" />
-
- @section scripts {
- <script>
- $(function () {
-
- let hubUrl = 'http://localhost:5000/reportsPublisher';
- let httpConnection = new signalR.HttpConnection(hubUrl);
- let hubConnection = new signalR.HubConnection(httpConnection);
-
- $("#publishReport").click(function () {
- hubConnection.invoke('PublishReport', $('#reportName').val());
- });
-
- hubConnection.start();
-
- });
- </script>
- }
Add Index View for Reports Controller.
- <h2>Reports</h2>
-
- <ul id="reports"></ul>
-
- @section scripts {
- <script>
- $(function () {
-
- let hubUrl = 'http://localhost:5000/reportsPublisher';
- let httpConnection = new signalR.HttpConnection(hubUrl);
- let hubConnection = new signalR.HubConnection(httpConnection);
-
- hubConnection.on('OnReportPublished', data => {
- $('#reports').append($('<li>').text(data));
- });
-
- hubConnection.start();
-
- });
- </script>
- }
Run both the Server and Client applications. You can open multiple instances of browser windows and observe the output.
Note
Publisher Controller acts as the reporting engine that notifies the server of report completion.
Source Code
GitHub