NashTech Blog

Table of Contents
man sitting in front of three computers

Introduction

In today’s fast-paced digital world, real-time communication is more crucial than ever. Whether it’s for chat applications, live updates, or notifications, the ability to instantly push information to clients has become a necessity. Fortunately, ASP.NET Core provides a powerful solution for real-time web functionality through SignalR.

What is SignalR?

SignalR is a library in ASP.NET Core that simplifies the process of adding real-time web functionality to applications. It enables server-side code to push content to connected clients instantly. With SignalR, you can build applications that support real-time updates for various scenarios such as chat applications, dashboards, live monitoring, and much more.

Key Features of SignalR

  1. Bi-directional Communication: SignalR allows both server-to-client (push) and client-to-server (send) communication seamlessly.
  2. Multiple Transport Options: SignalR supports various transport protocols such as WebSockets, Server-Sent Events (SSE), Long Polling, etc., ensuring compatibility with a wide range of clients and servers.
  3. Automatic reconnection: SignalR handles client reconnections automatically, ensuring a seamless user experience even in unstable network conditions.
  4. Hub-based Architecture: SignalR organizes communication through hubs, which act as endpoints for client-server communication. Hubs define methods that clients can invoke and vice versa.

Getting Started with SignalR in ASP.NET Core

Let’s dive into a simple example to demonstrate the basic usage of SignalR in an ASP.NET Core application.

Step 1: Create a new ASP.NET Core Project

Start by creating a new ASP.NET Core web application project in Visual Studio or using the .NET CLI.

Step 2: Install SignalR Package

Add the SignalR package to your project using NuGet Package Manager or the .NET CLI.

dotnet add package Microsoft.AspNetCore.SignalR.Common
Step 3: Define a SignalR Hub

Create a new class that inherits from Hub to define your SignalR hub. This class will contain methods that clients can invoke.

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
Step 4: Configure SignalR in Program.cs

I In the Program.cs file, add SignalR to the middleware pipeline and map the hub endpoint.

builder.Services.AddSignalR();

app.UseEndpoints(endpoints =>
{ 
    endpoints.MapHub<ChatHub>("/chat");
});
Step 5: Client Side Integration

Implement SignalR client-side code to establish a connection with the hub and receive messages.

<script  scr="https://cdn.jsdelivr.net/npm/@microsoft/signalr@8.0.0/dist/cjs/index.min.js"></script>
<script>
    var connection = new signalR.HubConnectionBuilder()
    .withUrl("/chat")
    .build();

    connection.start().catch(function (err) {
    return console.error(err.toString());
    });

    //Function to send message
    document.getElementById("sendmessage").addEventListener("click", function(event) {
    var user = document.getElementById("displayname").value;
    var message = document.getElementById("message").value;

    connection.invoke("SendMessage", user, message).catch(function (err) {
    return console.error(err.toString());
    });
    event.preventDefault();
    });

    // Function to Handle received message
    connection.on("ReceiveMessage", function (user, message) {
    var encodedMsg = user + ": " + message;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("discussion").appendChild(li);
    });
</script>
Step 6: Start the Application

Build and run your ASP.NET Core application. You should now have a basic SignalR-powered chat application up and running.

Conclusion

SignalR in ASP.NET Core provides a straightforward yet powerful way to implement real-time web functionality in your applications. Whether you’re building chat applications, live dashboards, or collaborative tools, SignalR simplifies the process of adding real-time capabilities, enhancing the user experience and making your applications more dynamic and responsive.

 

Picture of Siddhant Tiwari

Siddhant Tiwari

Leave a Comment

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

Suggested Article

Scroll to Top