Click here to Skip to main content
15,888,330 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.7K   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

 
QuestionTutorial not working due to error message about tampering HTTPS security Pin
KWHJ_JWHK8-Dec-17 3:27
KWHJ_JWHK8-Dec-17 3:27 
AnswerRe: Tutorial not working due to error message about tampering HTTPS security Pin
KWHJ_JWHK8-Dec-17 6:56
KWHJ_JWHK8-Dec-17 6:56 
SuggestionGreat tutorial! (suggestions for improvement) Pin
Shahed C5-Dec-17 14:40
Shahed C5-Dec-17 14:40 
Great tutorial! This worked for me with ASP .NET Core 2.0 on VS2017 v15.4.4 as of Dec 2017. I didn't have any issues with the alpha pre-release version of SignalR Core.

Here are some suggestions for improvement:
1. Index view for Home: You've included the View code for the Publisher and Reports controllers, but you missed the View code (list of links) for the Home controller.
2. Folder + filename for Shared Layout file: You've provided the view code for the Layout view, but you should also mention the filename and its folder name/location.
3. Helper views: You forgot to the mention the helper views _ViewImports.cshtml and _ViewStart.cshtml. These are included in the source code on GitHub, but it would also be helpful to mention them in the tutorial as well.

Hope that helps! Smile | :)
QuestionHost server application with public url Pin
shubamkiet9-Oct-17 21:08
shubamkiet9-Oct-17 21:08 
AnswerRe: Host server application with public url Pin
User 104326410-Oct-17 3:04
User 104326410-Oct-17 3:04 
GeneralRe: Host server application with public url Pin
shubamkiet10-Oct-17 19:23
shubamkiet10-Oct-17 19:23 
GeneralRe: Host server application with public url Pin
User 104326411-Oct-17 2:01
User 104326411-Oct-17 2:01 
GeneralRe: Host server application with public url Pin
shubamkiet12-Oct-17 1:36
shubamkiet12-Oct-17 1:36 
GeneralRe: Host server application with public url Pin
User 104326412-Oct-17 3:29
User 104326412-Oct-17 3:29 
GeneralRe: Host server application with public url Pin
shubamkiet26-Oct-17 19:57
shubamkiet26-Oct-17 19:57 
QuestionSending a Message from console to web client Pin
Smatronic14-Sep-17 1:06
Smatronic14-Sep-17 1:06 
AnswerRe: Sending a Message from console to web client Pin
User 104326414-Sep-17 2:24
User 104326414-Sep-17 2:24 
GeneralRe: Sending a Message from console to web client Pin
Smatronic14-Sep-17 21:28
Smatronic14-Sep-17 21:28 
GeneralRe: Sending a Message from console to web client Pin
User 104326414-Sep-17 21:59
User 104326414-Sep-17 21:59 
GeneralRe: Sending a Message from console to web client Pin
Smatronic15-Sep-17 1:22
Smatronic15-Sep-17 1:22 
QuestionWhere is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok8-Sep-17 10:23
dkurok8-Sep-17 10:23 
AnswerRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
User 10432648-Sep-17 12:03
User 10432648-Sep-17 12:03 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok9-Sep-17 3:47
dkurok9-Sep-17 3:47 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
User 10432649-Sep-17 4:15
User 10432649-Sep-17 4:15 
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 

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.