Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET / ASP.NET Core

ASP.NET Core 2.0 & SignalR Core (alpha)

Rate me:
Please Sign up or sign in to vote.
5.00/5 (9 votes)
6 Sep 2017CPOL2 min read 44.1K   13   28
How to use SignalR Core in ASP.NET Core 2.0 web applications to provide real-time communication. Continue reading...

Problem

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. 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:

  • Microsoft.AspNetCore.All
  • Microsoft.AspNetCore.SignalR

Update Program class:

C#
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:

C#
public class Startup
    {
        public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("fiver",
                    policy => policy.AllowAnyOrigin()
                                    .AllowAnyHeader()
                                    .AllowAnyMethod());
            });

            services.AddSignalR(); // <-- SignalR
        }

        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env)
        {
            app.UseCors("fiver");

            app.UseSignalR(routes =>  // <-- SignalR
            {
                routes.MapHub<ReportsPublisher>("reportsPublisher");
            });
        }
    }

Create a class that inherits from SignalR Hub class:

C#
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:

C#
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.:

C#
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:

HTML
<!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:

HTML
<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:

HTML
<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 could open multiple instances of browser windows and observe the output:

Image 2

Note: Publisher controller acts as the reporting engine that notifies the server of report completion.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok9-Sep-17 4:53
dkurok9-Sep-17 4:53 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
User 10432649-Sep-17 5:00
User 10432649-Sep-17 5:00 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok9-Sep-17 5:14
dkurok9-Sep-17 5:14 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
User 10432649-Sep-17 5:19
User 10432649-Sep-17 5:19 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok9-Sep-17 5:28
dkurok9-Sep-17 5:28 
QuestionUpdate please Pin
codejockie7-Sep-17 21:54
professionalcodejockie7-Sep-17 21:54 
AnswerRe: Update please Pin
User 10432647-Sep-17 22:08
User 10432647-Sep-17 22:08 
GeneralMy vote of 5 Pin
Robert_Dyball7-Sep-17 10:54
professionalRobert_Dyball7-Sep-17 10:54 
Thank you!
handy, short and to the point, just what I needed to save time.
GeneralRe: My vote of 5 Pin
User 10432647-Sep-17 12:12
User 10432647-Sep-17 12:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.