How to Build a Web App with SignalR in .NET Core?
When it comes to building applications, one of the most well-liked libraries for.NET development
company is SignalR. When developers design an application with real-time capability, they connect
the server-side code content to every client as soon as it becomes available, instead of waiting for
each client to request fresh data from the server. A bidirectional communication channel is provided
by the SignalR communication service between the application’s client and server sides.
Additionally, this service can be utilized for any online page or application that employs
JavaScript or the.NET Framework 4.5, not just web applications.
Let’s read this blog to learn more about SignalR, including its requirements,
how to use it with.NET Core, and other things.
What is SignalR?
One of the most widely used open-source tools that makes it easier for developers to add reliable,
real-time online functionality to applications is ASP.NET Core SignalR. When a request is received,
real-time web functionality enables the server-side code to provide the stream data to the client
side instantaneously. This means that, rather than waiting for a new request from the client to send
data back, the server-side code in a real-time enabled process is developed so that it quickly
provides content or data to the connected client as soon as it becomes available.
Assume, for example, that the real-time application is a chat program. In this case, as soon as the
client is available, the server provides data and messages to the client. Within the web
application, messages can also be sent as push notifications using the SignalR service in this
situation. In this case, SingalR creates a secure communication channel using encryption and a
digital signature.
Some of the good candidates for SignalR service are :
Instant sales updates, company
dashboards, and travel warnings are a few examples of dashboard and monitoring apps that make
excellent candidates for SignalR.
.NET Core Applications can now
require high-frequency updates from the server side thanks to SignalR.
These are the apps that require
instantaneous real-time updates. Examples include applications for social networking, gaming,
GPS, voting, auctions, and mapping
SignalR is responsible for apps like
chat, travel alerts, games, social networks, and other apps that need real-time notifications.
The ideal applications for SignalR
service are collaborative ones, like whiteboard and team meeting software.
An API is provided by the SignalR Net Core service to create remote procedure calls (RPCs) that
transfer data from the server to the client. Server-side code can call different functions on
clients through the use of remote procedure calls. In this instance, there are various supported
platforms with corresponding client SDKs. As a result, different programming languages are invoked
by the RPC call.
Features of SignalR Service
Using this method, messages can be transmitted concurrently to every client that is connected.
With SignalR’s assistance, connection management is automatically handled by developers.
It is possible to send messages to particular clients or groups using the SignalR service.
One of this service’s most crucial features is the SignalR Hub protocol.
This service can grow to accommodate more users.
Basic Knowledge of ASP.NET Core
An additional requirement for SignalR is a working grasp of the general-purpose software solution
development framework,.NET Core. It makes it possible for .NET developers to construct a wide range
of software applications, including gaming, cloud, mobile, web, desktop, and more. Additionally, in
order to begin using the SignalR service, a basic understanding of this technology is necessary.
Steps to Implement SignalR in .Net Core
Let’s now examine the procedures that developers can use to configure and implement SignalR in
ASP.NET Core:
Making a web application project with the ASP.NET Core framework is the first step. As you can see,
in order to implement SignalR, we must first create a.NET web application. With that in mind, let’s
walk through the process of defining methods.
Therefore, in order to use SignalR in ASP.NET Core, developers must first include the SignalR client
library in the project for the web application. The instructions in the screenshot must be followed
in order to add the SignalR client library.
In Solution Explorer, right-click the project, and select Add > Client-Side Library.
Add Client-Side Library dialog:
- Select unpkg for Provider
- Enter @microsoft/signalr@latest for Library.
- Select Choose specific files, expand the dist/browser folder, and select signalr.js and
signalr.min.js.
- Set Target Location to wwwroot/js/signalr/.
- Select Install.
After you are done with the installation process, it’s time to create SignalR Hub: ChatHub Class. To
do so, follow the below given .NET SignalR code.
ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalrImplementation.Models
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
Now after that, you need to add a service reference in the startup.cs’s ConfigureServices method.
For that follow the below code.
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSignalR();
}
Now, you can add a chat hub class in the Configure method in startup.cs as shown in the below code.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseSignalR(routes =>
{
routes.MapHub("/chatHub");
})
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
After this, it’s time to create a new JavaScript file for HubConnection, as soon as in the below
code.
chat.js
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.on("ReceiveMessage", (user, message) => {
const msg = message.replace(/&/g, "&").replace(//g, ">");
const encodedMsg = user + " :: " + msg;
const li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(err => console.error(err.toString()));
Send the message
document.getElementById("sendMessage").addEventListener("click", event => {
const user = document.getElementById("userName").value;
const message = document.getElementById("userMessage").value;
connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
event.preventDefault();
});
This was all about the logic that goes behind the implementation process. Now it’s time to create a
User Interface for the Chat test.