Click here to Skip to main content
13,248,927 members (44,471 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

9K views
9 bookmarked
Posted 6 Sep 2017

ASP.NET Core 2.0 & SignalR Core (alpha)

, 6 Sep 2017
Rate this:
Please Sign up or sign in to vote.
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:

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(); // <-- 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:

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

License

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

Share

About the Author

Tahir Naushad
Software Developer (Senior)
United Kingdom United Kingdom
Qualified and skilled professional with experience working as a Software Developer, Technical Lead and Architect. I have worked on windows, web and distributed applications using the latest set of technologies within the Microsoft .NET ecosystem. I have lead teams using agile methodologies and trained developers in writing well-designed and maintainable software applications.

Currently focusing on ASP.NET Core, C#, Azure, Angular and Domain Driven Design.

You may also be interested in...

Comments and Discussions

 
QuestionHost server application with public url Pin
shubamkiet9-Oct-17 22:08
membershubamkiet9-Oct-17 22:08 
AnswerRe: Host server application with public url Pin
Tahir Naushad10-Oct-17 4:04
memberTahir Naushad10-Oct-17 4:04 
GeneralRe: Host server application with public url Pin
shubamkiet10-Oct-17 20:23
membershubamkiet10-Oct-17 20:23 
GeneralRe: Host server application with public url Pin
Tahir Naushad11-Oct-17 3:01
memberTahir Naushad11-Oct-17 3:01 
GeneralRe: Host server application with public url Pin
shubamkiet12-Oct-17 2:36
membershubamkiet12-Oct-17 2:36 
GeneralRe: Host server application with public url Pin
Tahir Naushad12-Oct-17 4:29
memberTahir Naushad12-Oct-17 4:29 
GeneralRe: Host server application with public url Pin
shubamkiet26-Oct-17 20:57
membershubamkiet26-Oct-17 20:57 
QuestionSending a Message from console to web client Pin
Alexander baloch14-Sep-17 2:06
memberAlexander baloch14-Sep-17 2:06 
AnswerRe: Sending a Message from console to web client Pin
Tahir Naushad14-Sep-17 3:24
memberTahir Naushad14-Sep-17 3:24 
GeneralRe: Sending a Message from console to web client Pin
Smatronic14-Sep-17 22:28
memberSmatronic14-Sep-17 22:28 
GeneralRe: Sending a Message from console to web client Pin
Tahir Naushad14-Sep-17 22:59
memberTahir Naushad14-Sep-17 22:59 
GeneralRe: Sending a Message from console to web client Pin
Smatronic15-Sep-17 2:22
memberSmatronic15-Sep-17 2:22 
QuestionWhere is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok8-Sep-17 11:23
memberdkurok8-Sep-17 11:23 
AnswerRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
Tahir Naushad8-Sep-17 13:03
memberTahir Naushad8-Sep-17 13:03 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok9-Sep-17 4:47
memberdkurok9-Sep-17 4:47 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
Tahir Naushad9-Sep-17 5:15
memberTahir Naushad9-Sep-17 5:15 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok9-Sep-17 5:53
memberdkurok9-Sep-17 5:53 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
Tahir Naushad9-Sep-17 6:00
memberTahir Naushad9-Sep-17 6:00 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok9-Sep-17 6:14
memberdkurok9-Sep-17 6:14 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
Tahir Naushad9-Sep-17 6:19
memberTahir Naushad9-Sep-17 6:19 
GeneralRe: Where is the nuget-package Microsoft.AspNetCore.SignalR Version="1.0.0-alpha1-26918" Pin
dkurok9-Sep-17 6:28
memberdkurok9-Sep-17 6:28 
QuestionUpdate please Pin
codejockie7-Sep-17 22:54
professionalcodejockie7-Sep-17 22:54 
AnswerRe: Update please Pin
Tahir Naushad7-Sep-17 23:08
memberTahir Naushad7-Sep-17 23:08 
GeneralMy vote of 5 Pin
Robert_Dyball7-Sep-17 11:54
professionalRobert_Dyball7-Sep-17 11:54 
GeneralRe: My vote of 5 Pin
Tahir Naushad7-Sep-17 13:12
memberTahir Naushad7-Sep-17 13: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 7 Sep 2017
Article Copyright 2017 by Tahir Naushad
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid