Real-time communication using SignalR and .NET Core: A step-by-step guide
Tags: dotnet, signalr, webdev, programming
Published: 2022-10-17 04:53:35

Do you know SignalR can help you establish real-time communication for your business and push content updates to your clients? This two-way request-response protocol makes communication extremely easy for the business and works independently of transport protocols. You might be surprised to learn that SignalR can compel a server to supply data without a request and have your website section auto-refresh as new data becomes available. It is further responsible for connection persistence and high-traffic management.

This post will explain in detail what SignalR is and how it can help you set up real-time communication step by step. But before diving into the nuts and bolts of the topic, let’s take a look at its history.

## Introduction to SignalR

David Fowler and Damian Edwards, who now play significant roles in the direction and development of ASP.NET, founded SignalR in 2011. It was included in the ASP.NET project and made public in 2013 as a component of ASP.NET. The WebSocket protocol hadn't yet been standardized at the time, and the majority of browsers didn't support it.

Inefficient methods like AJAX polling and long-polling, as well as technologies like server-sent events that weren't widely supported by browsers, were employed by developers to construct real-time messaging for the Web. By developing server- and client-side libraries that abstract away the complexities of these technologies, SignalR was created to address this issue and provide simple support for real-time capabilities on the ASP.NET stack.

On the Internet, a lot may change in five years. Since practically all web applications at the time SignalR was developed used jQuery, it was a simple decision for the SignalR JavaScript client to do the same. Before the WebSocket protocol was generally embraced by browsers, SignalR also had complicated logic aimed at managing various protocols and workarounds to accomplish real-time messaging on the Web.3

## Looking to [hire .NET Core developers](https://www.ifourtechnolab.com/hire-dot-net-core-developer)? Your search ends here.

Other features of SignalR that were intended to make it easier to use were automatic reconnection and turnkey scale-out, but they instead made the framework more complicated and inefficient.

When ASP.NET was rebuilt from the ground up to produce a faster, cross-platform ASP.NET Core, the team took the effort to entirely redesign SignalR. They accomplished this in order to include all the lessons learned from the past two versions of SignalR and make it flexible enough to withstand any new protocols and transport technologies in the future.

## Overview of ASP.NET Core SignalR

SignalR requires ASP.NET Core 2.1 to interact with .NET Core. It is accessible by this route.

Hubs are still the major route of communication between the server and its users. This is related to the practice of clients calling a hub and the hub calling clients in order to simplify operations. It maintains connections that have been invoked by a specified method. To add more, they can send a message to a single connection, all connections associated with the user, or connections in arbitrary groups.

SignalR is the most crucial aspect of .NET Core application development since it enables real-time data exchange. Sometimes users want real-time data updates in the application without requiring any end-user intervention; in this scenario, SignalR comes in handy.

Now let’s go through the ins and outs of SignalR in the .NET Core.

An open-source toolkit called SignalR ASP.NET Core makes it simple to include the real-time online capability in applications. It can fulfill the demand for frequent server updates and may immediately push content to clients thanks to its real-time web capability.

SignalR is the best choice for the following kind of applications.

- Alerting and notifications
- Chat applications
- Online Gaming

## Read More: [ASP.NET SignalR for real time applications](https://www.ifourtechnolab.com/blog/asp-net-signalr-for-real-time-applications)

## How SignalR works in ASP.NET Core?

ASP.NET Core enables support for SignalR through internal and individual Protocols. A new JSON message protocol that is incompatible with SignalR's older versions is included in ASP.NET Core SignalR. Additionally, it contains a second integrated protocol built on the foundation of Message Pack, a binary protocol with smaller payloads than text-based JSON.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/19uukm04ivqp58zvwdy3.png)

ASP.NET Core SignalR provides extensibility points that allow new protocols to be plugged in if you want to design a unique message protocol.

## What are the advantages of SignalR?

SignalR assists organizations in implementing a real-time chatroom application that can be used by several users at the same time and provides an excellent user experience.

This real-time communication library broadcasts messages to a single client or a group of clients, depending on the business scenario. It is simple to use and keeps clients informed through alert messages, news feed updates, or offers of some sort.

#### Dependency injection

Although ASP.NET does not support dependency injection, SignalR does by providing a Global Host class with its own dependency resolver. Since ASP.NET Core comes with an inversion of control (IoC) container, ASP.NET Core SignalR only makes use of the framework that is already present for dependency injection.

Hubs in ASP.NET Core SignalR now enable function Object() [native code] dependency injection without further setup, just as ASP.NET Core controllers or razor pages. By obtaining an IHubContext from the IoC container and utilizing its methods to deliver messages to the hub's clients, it is also simple to access a hub's context from outside the hub itself.

#### Transport priority

The following methods for handling real-time communication are supported by SignalR.

- WebSockets
- Server-Sent Events
- Long Polling

It automatically chooses the best transport method.

## Searching for a trusted [.NET development company](https://www.ifourtechnolab.com/dot-net-development-company)? Contact us now.

#### Using Hubs to communicate
SignalR makes use of the hubs class to communicate between clients and servers. It allows clients to invoke server-side methods and clearly distinguishes between real-time messaging and the hosting environment.

#### Real-time response
Businesses that desperately require to handle client-server communication, want auto-updating situations on the site, and want to save significant time might benefit from SignalR. Because it manages real-time traffic and connection persistence effortlessly.

Now, let's see how SignalR works in practice by creating a real-time project and calling SignalR broadcast.

## How to implement SignalR in ASP.NET Core?

SignalR, as we all know, is an excellent way to rapidly add real-time collaborating capabilities to a web application. Because it is the platform that handles connection persistence, frequent content modifications, and real-time traffic smoothly.

#### Prerequisites:

Before we get into the details, it's important to understand the fundamental requirements for building SignalR in .NET Core:

- Basic knowledge of ASP.NET Core
- .NET Core 3.1 or later version installed
- An IDE such as JetBrains Rider or VS Code, Visual Studio
- Postman or similar for testing API calls

#### Required software:

- Visual Studio Version 15.7.3 (2017) or later
- Node package manager(npm) -  https://docs.npmjs.com/getting-started
- .NET Core SDK 2.1 or later - https://dotnet.microsoft.com/en-us/download

## Read More: [Why ASP.NET Core is best for Enterprise Web Application Development?](https://www.ifourtechnolab.com/blog/why-asp-net-core-is-best-for-enterprise-web-application-development)


## Steps to implement SignalR in .Net Core
Step 1: Open Visual Studio and create a .NET Core web application.

Step – 2: Now, we need to include SignalR client library in the project. To do so, go to solutions explorer, right-click on the project then Add > Client-side library.

Step – 3: In the "Add Client-side Library" window, select unpkg from the dropdown, and choose the most recent library version (for example, @microsoft/signalr@6.0.7) under the Library.

Step – 4: Select “Choose specific files” and then you can see nested folders such as Files, dist, and browser. Expand them and select signalR.

Step – 5: click on “install” to proceed with the installation.

Here is the reference screenshot to add the SignalR client library.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/opqj5f9ullsmhfs1ankv.png)

Step – 6: When you finish the installation, build a SignalR Hub: ChatHub Class using the following code.

**chathub.cs**

```

<xmp>
namespace SignalrProject.Models
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync(&quot;ReceiveMessage&quot;, user, message);
        }
    }
}
</xmp>

```

Step – 7: Then, Add the service reference in startup.cs > ConfigureServices function.

**startup.cs**

```
<xmp>
public void ConfigureServices(IServiceCollection services)
  {
    services.AddControllersWithViews();
    services.AddSignalR();
 }

</xmp>

```

Step – 8: In startup.cs, we will add the Chathub class under the Configure function.

**startup.cs**

Looking for a reliable [Microsoft Azure development company](https://www.ifourtechnolab.com/microsoft-azure-cloud-services-development-company)? Contact us now.

```

<xmp>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
            &hellip;&hellip;&hellip;&hellip;&hellip;
            app.UseSignalR(routes =>
            {
                routes.MapHub(&quot;/chatHub&quot;);
            })
            &hellip;&hellip;&hellip;&hellip;&hellip;
  }

</xmp>

```

Step – 9: Next, we'll need to make a new JS file for HubConnection. To do so, follow the procedures outlined in the code. Let’s name it chat.js.

**chat.js**

```

<xmp>

const connection = new signalR.HubConnectionBuilder()
    .withUrl(&quot;/chatHub&quot;)
    .build();
 
connection.on(&quot;ReceiveMessage&quot;, (username, message) => {
    const msg = message.replace(/&/g, &quot;&&quot;).replace(//g, &quot;>&quot;);
    const encodedMsg = username + &quot; :: &quot; + msg;
    const li = document.createElement(&quot;li&quot;);
    li.textContent = encodedMsg;
    document.getElementById(&quot;messagesList&quot;).appendChild(li);
});

connection.start().catch(err => console.error(err.toString()));

// code for send the message 

document.getElementById(&quot;sendMessage&quot;).addEventListener(&quot;click&quot;, event => {
    const username = $(&quot;userName&quot;).val();
    const message = $(&quot; userMessage &quot;).val();
    connection.invoke(&quot;SendMessage&quot;, username, message).catch(err => console.error(err.toString()));
    event.preventDefault();
}); 

</xmp>

```

We have successfully implemented the logical process to this point. It is now time to design a chat test user interface.

Step – 10: To develop a chat test user interface, create an index.cshtml file and follow the coding instructions provided.

Read More: [13 Important .Net Core Libraries that Every .Net Core Developer Should Know](https://www.ifourtechnolab.com/blog/13-important-net-core-libraries-that-every-net-core-developer-should-know)

**index.cshtml**

```

<xmp>

// code for index file
@page<div class="container"><div class="row"> </div>
<div class="row"><div class="col-md-12"><div class="col-md-6"><div class="col-md-3">User</div>
<div class="col-md-9"><input id="userName" type="text" /></div></div></div>
<div class="col-md-12"><div class="col-md-6"><div class="col-md-3">Message</div>
<div class="col-md-9">
                    <input id="userMessage" type="text" />
                    <input id="sendMessage" type="button" value="Send Message" /></div></div></div></div>
<div class="row"><div class="col-12"><hr /></div></div>
<div class="row"><div class="col-6"> </div>
<div class="col-6"><ul id="messagesList"></ul></div></div></div>
<script src="~/lib/microsoft/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>


</xmp>

```

Here we go!! The SignalR implementation in .NET Core is now complete. Run the application in your browser and you will see the following output.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yoy54hosyq665soxv4za.png)

### Conclusion

SignalR has been a terrific solution for establishing real-time customer communication for the business. It operates independently of transport standards and aids in delivering content updates to connections. It forces the server to deliver data without a request and causes your website area to reload automatically when new data becomes available. In this post, we learned about SignalR, its benefits, essential needs, and how to effectively create real-time communication with SignalR in ASP.NET Core.