Real-Time Web using SignalR (.NET6, Browser-Client and NodeJS)

Introduction

ASP.NET Core SignalR is an open-source library that simplifies adding real-time web functionality to applications. It enables server-side code to push content to clients instantly.

Maps, Dashboards, Chat systems, Collaborate apps and different type of push notifications etc. are few of the good candidates for real-time functionality / SignalR.

In this post, we’ll see a simple setup which you can use as a starter template for these type of applications. However, we’ll not go into the details about why need for real-time applications? the SignalR technology, its different fallback transport mechanisms, best practices etc.

The goal is to have a basic understanding of SignalR, how to set it up easily and and along the way we will cover some core concepts and code samples.

SignalR Basics

Lets see a diagram of how SignalR Hub enables communication from Server to Browser/Client:

  • Using the Hub class, messages can be sent to client(s) and group.
  • SignalR uses Remote Procedure Calls (RPC).

For more information about SignalR, you can check the official documentation on this link.

Initial Project Setup

Lets start setting up things. For SignalR itself, we’ll host it inside a Web API project. So SignalR can live side-by-side with other API code such as Controllers etc.

I’ve created a .NET6 Web API application using built-in template as shown below:

All demos Source code is available from this git repository.

Next, setup the SignalR as shown follows by updating Program.cs file:

With these two lines, we have wired up a SingalRHub to an endpoint.

Hub is the main component when using SignalR.

Lets see the ProductHub class next

The ProductHub (which is wired in the startup) have a method SendMessagetoAll(), which we can use to send message to all connected clients. Its a typical C# class which inherit from built-in Hub class and with that we have access to various objects like Clients, Context etc. offered by Hub and we can use functions offered by these communication, context type of objects.

So at this point, we have wired-up a ProductHub into our WebApi application which is ready to server calls on method SendMessageToAll().

Who will call this method? we will cover it next.

Demo Overview

Lets check the following diagram which we’re going to implement:

So, a client application can be another .NET console app e.g. or a JavaScript application running in browser (we will see an example later) or the likes e.g. NodeJS application.

NodeJS application as a SignalR Client

We can run JavaScript outside of browser context using NodeJS. Don’t worry if you don’t know NodeJS, it will be just few line of very simple JavaScript code to do a quick test and later we will see a browser example as well.

we can use npm to install JavaScript SignalR package and then use it in our code:

npm install @microsoft/signalr

With this code, now, if we execute index.js code using Node, it will make a SignalR connection to a specified Hub endpoint and will invoke a method on the Hub (SendMessageToAll) with “Hello” data.

Now, on the server side (Hub), once it receive the call with “Hello” data, it will add some text to this data and then call a method (methodOnClient) for each connected client. See the following server code from earlier for recall:

So lets see the result when we execute the code with Node.js:

as you can see from code execution that call was made to Hub and then hub called back all the clients and our NodeJS code received the message and then write it to console.

Let sink this in, and if needed, check the previous diagram again to see how the communication flows.

Using Hub Inside A Controller to Send Message to Clients

Lets consider another scenario, where a user enters a new Product or Delete Product etc. e.g. using a web UI via a REST API call and once the operation is performed on the server, we can update the connected Clients (users) with some data e.g. to refresh the table data on UI or show a notification dialog and the likes. Lets see this in a demo:

I’ve added a typical Web API controller ProductController as follows:

The code is self explanatory, it is a very simple controller where IHubContext<ProductHub> is injected via Dependency Injection (due to the wiring in Program.cs file) and as you can see that we are using it to call a method (“methodOnClient”) from inside our controller GetAction, which is triggered due to a REST/HTTP call.

Lets test calling this method via Postman tool and see if our connected NodeJS application receives this information:

as we can see that it worked as expected.

Browser Application (JavaScript) as a client

Browser JavaScript applications are candidates for Realtime web functionality to notify users, updated UI components and the likes.

Basically, the setup is same like we saw earlier in NodeJS application, we can use same SignalR package in our browser JavaScript applications.

If you are using a framework e.g. Angular, React etc. then you will find appropriate libraries/packages etc. on the official web pages.

For this demo, we will keep it simple, will use npm to download the SignalR package and use it in the code.

Also, I’ll be using ParcelJS as a bundler but you can use any set of tools as per your setup.

If you are interested in learning more about ParcelJS setup, you can check this post.

The following picture shows markup of index.html page which has index.js JavaScript code:

and following is the corresponding JavaScript index.js file code which is referencing SignalR package.

inside the constructor, we can see that SignalR related code which is very similar to what we saw earlier on NodeJS example:

basically, we are wiring with SignalR events and using few of its methods with typical JavaScript application code. Here it is not doing much, simply it is starting a connection and calling a method on Hub “SendMessageToAll()” and then also when a method-call is received from server, corresponding handler code is executed.

With all this in place, lets put this to test by running the browser application (npm run dev) and here we have the following situation:

It is a security feature from browser and in order to get this work, we need to enable CORS on .NET Core Web API project as follows:

Test again and this time, we can see that browser application is able to communicate with server and server can call methods on client:

Testing all together

The following diagram shows testing of all these components together:

and here are the test results

As you can see that different clients are receiving method calls from the server and real-time communication is enabled.

Even though our demo is very basic and almost nothing on the UI, but you can see that our application have push capabilities, so instead of clients requesting the data and server sending the response, updates can be pushed automatically to clients along-side typical request/response model.

That’s all for today and now we have basic communication setup among various entities and we can use these learning to setup projects easily to enable SignalR communication.

In some later posts, we will build on top of this setup and advance our learnings.

Summary

In this post, we saw simple setup to use SignalR in a .NET6 web application which enables real-time communication with client applications (SignalR clients).

Source-code from the demos is available from this git-hub repository.

Let me know if you have some questions or comments. Till next time, happy coding.

My Recent Books