Real-time Web Applications with SignalR in ASP.NET Core 3.1

In this article, we will learn about real-time web & how to build real-time web applications using SignalR in ASP.NET Core. As part of this article, we will work on an application that can send real-time messages/alerts to all connected users or private messages to some specific user(s).

I will upload the entire source code for the real-time web application, developed as part of this article, to GitHub & provide the link for the same at the end of this article.

Introduction to Real-time Web Applications

Real-time web applications allow users to receive the latest information, like messages, alerts, or application/user-specific data, as soon as data changes (add/modify/delete) on the server without the need for the user to request the data.

There are many examples of real-time applications one of them is Gmail which displays new emails without the need for users to refresh or reload. Web application from stock exchanges is one of the greatest examples of real-time web applications where stock prices are communicated to connected browsers without the need for clients to request the data. SignalR in ASP.NET Core is used to build real-time web applications.

Also, there is a need for real-time data transmitting from IoT devices. Alerts from IoT devices like any change in monitored parameters should be processed and forwarded to users without any delay. Also, vise-versa i.e. commands from users should reach IoT devices without any delays.

In the case of real-time applications, the server should be smart enough to detect changes and send changes to connected clients i.e. browsers.

Introduction to SignalR

SignalR in ASP.NET Core

SignalR is a library that can be used to develop real-time web applications in ASP.NET Core. SignalR contains an API that allows server-side code to send messages to connected client browsers.

SignalR in ASP.NET Core uses Remote Procedure Call to enable the server to call a function on the client using underlying transport.

SignalR in ASP.NET core allows running on many platforms, other than windows, which are supported by ASP.NET Core.

Get Started with IOT using CanaKit Raspberry Pi 4 4GB Starter MAX Kit - 64GB Edition

SignalR Transports

SignalR uses transports for sending messages from server to client. Following Transports are supported by SignalR

  • Long Polling
  • Server-Sent Events
  • WebSockets

SignalR in ASP.NET Core has provided a wrapper around these low-level transports which allow developers to just focus on business requirements instead of worrying about these low-level programming. Based on the browser version used SignalR automatically decides, using a fallback mechanism, about the underlying transport to be used.

WebSockets is the most efficient transport but this requires the latest browser and if the client is running an old browser then SignalR will fall back on Server-Sent events & if that is also not supported then will fall back on long polling.

SignalR Hub

SignalR uses hubs to communicate between clients & servers. Hub is a component that is hosted in your ASP.NET Core Application. Hub sends messages to & receives messages from the client using a remote procedure call using underlying transport.

A combination of hub & remote procedure call enables real-time web applications using SignalR in ASP.NET Core. Hub in ASP.NET Core application is a class derived from hub base class.

Getting Started with SignalR in ASP.NET Core

This will get you started with implementing SignalR in ASP.NET Core MVC Web Application.

Create ASP.NET Core MVC project for demonstration

For demonstration purposes, we will be creating a default ASP.NET Core 3.1 MVC Project using Visual Studio 2019 Community Edition. Create a project as per the screenshots shown below

Create Visual Studio Project
Create Visual Studio Project
Create Visual Studio Project

Install required packages for SignalR

The server library for SignalR is included in ASP.NET Core 3.1 framework but the client-side JavaScript library needs to be added to the project for SignalR in ASP.NET Core

  • In Solution Explorer right click on wwwroot & select Add->Client Side Library
  • Select providerunpkg‘ & enter ‘@microsoft/[email protected]‘ for library
  • Choose specific files to be added, set target location & click on install
Visual Studio - Add Client Side Library
Visual Studio - Add Client Side Library
SignalR in ASP.NET Core in Solution Explorer

Create a SignalR Hub

Hub is a class that handles client-server communication in SignalR in ASP.NET Core. The client connects to the hub to receive messages. Create a hub class, which derives from base class Hub, as shown in the below code.

public class MessageHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        if (string.IsNullOrEmpty(user))
            await Clients.All.SendAsync("ReceiveMessageHandler", message);
        else
            await Clients.User(user).SendAsync("ReceiveMessageHandler", message);
    }
}

Hub SendMessage method takes 2 parameters i.e. user to which message is to be sent and message itself which is to be sent. Now if user is blank then message will be sent to all connected users and if user is specified then it will be sent only to that specified user.

Hub calls SendAsync method that takes 2 parameters, first one is the method name ‘ReceiveMessageHandler’ which is called on the client using remote procedure call so each client connecting to this hub has to implement this method to receive messages from hub & other is the message itself which will be passed to client method ‘ReceiveMessageHandler’ while calling that method.

Configure SignalR in ASP.NET Core Application

Configure SignalR in the project by adding the following code to ConfigureServices & Configure method in a startup.cs file

using ProCodeGuide.Sample.SignalR.Hubs;

public class Startup
{
	//Remaining code has been removed for readability. Full code is available for download below
	
	// This method gets called by the runtime. Use this method to add services to the container.
	public void ConfigureServices(IServiceCollection services)
	{
		//Remaining code has been removed for readability. Full code is available for download below
		services.AddSignalR();
	}

	// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		//Remaining code has been removed for readability. Full code is available for download below
		app.UseEndpoints(endpoints =>
		{
			endpoints.MapHub<MessageHub>("/messagehub");
		});
	}
}

Here SignalR service is configured in ConfigureServices method & endpoint is added for MessageHub in Configure method which will be used by the client to connect to the SignalR Hub.

Wire the UI

Now let’s add the client code to connect to the hub, add ‘receiveMessageHandler’ method which will be called by MessageHub while sending message to client & also add user interface to allow users to send message to all other users or to a specific user.

Add JavaScript code to connect to Hub & Message receive Method

JavaScript file ConnectSignalR.js is added with below code on path wwwroot/js/ that will connect client to MessageHub & also implements client function ‘ReceiveMessageHandler’ to receive messages from hub.

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/messagehub").build();

connection.start();

connection.on("ReceiveMessageHandler", function (message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    alert(msg);
});

Now lets load this JavaScript file in _Layout.cshtml file after successful login i.e. for authenticated users as shown below

@if (SignInManager.IsSignedIn(User))
{
    <script src="~/lib/microsoft/signalr/dist/browser/signalr.js"></script>
    <script src="~/js/ConnectSignalR.js"></script>
}

This will load a client library file for SignalR and also connect the client to MessageHub for authenticated users.

Create Send Message cshtml

Let’s create a user interface that will allow users to send messages to all or specific users. Note that I will be adding this view for all users i.e. any logged-in user can access this view but if need be then this form can be restricted to admins only for the capability to send messages/alerts to connected users.

Following view is added under Views/Home/SendMessage.cshtml

@page

<div class="container">
    <div class="row">&nbsp;</div>
    <div class="row">
        <div class="col-2">To User</div>
        <div class="col-4"><input type="text" id="userInput" /></div>
    </div>
    <div class="row">
        <div class="col-2">Message</div>
        <div class="col-4"><input type="text" id="messageInput" /></div>
    </div>
    <div class="row">&nbsp;</div>
    <div class="row">
        <div class="col-6">
            <input type="button" id="sendButton" value="Send Message" />
        </div>
    </div>
</div>
<script src="~/js/SendMessage.js"></script>

Below is the JavaScript file ‘SendMessage.js which has been added on path wwwroot/js/ to call hub method on the server using remote procedure call.

"use strict";

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

As MessageHub function SendMessage takes 2 parameters accordingly user & message has been passed to call SendMessage function.

Add SendMessage action to Home controller

Add action method to load view SendMessage in HomeController.cs

[Authorize]
public IActionResult SendMessage()
{
    return View();
}

Finally let’s add the link to call above action to load view SendMessage. Again Send Message link is added only for authenticated users as shown below.

@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="SendMessage">Send Message</a>
    </li>
}

The above code has been added in _Layouts.cshtml file under the list for navigation items.

Run the code & check

Before you run the code don’t forget to execute the below-mentioned commands in the package manager console to automate the migrations & create the database.

add-migration InitialMigration
update-database

After running the code register at least 3 users and log in with all 3 users from different browsers to test send message functions for all & specific users. Here are the test results for SignalR in ASP.NET Core Application.

SignalR in ASP.NET Core Test 1
3 users logged in to application
SignalR in ASP.NET Core Test 2
Message sent to all users
SignalR in ASP.NET Core Test 3
Message sent to only one user

Summary

In this article we learned in detail about what are real-time application, SignalR & how to get started with SignalR in ASP.NET Core. Complete source code which was developed as part of this article is available on GitHub and link for same is provided at end of this article.

Download Source Code

What is Real Time Web?

Real-time web applications allow users to receive the latest information, like messages, alerts, or application/user-specific data, as soon as data changes (add/modify/delete) on the server without the need for the user to request the data.

What is SignalR?

SignalR is a library that can be used to develop real-time web applications in ASP.NET Core.

How SignalR Works?

SignalR contains an API that allows server-side code to send messages to connected client browsers.

Which Transports are supported in SignalR?

SignalR support transports long polling, Server Sent Events & WebSockets in ASP.NET Core.

Hope you found this article useful
Buy me a coffeeBuy me a coffee

2 thoughts on “Real-time Web Applications with SignalR in ASP.NET Core 3.1

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *