How to Implement SignalR in .NET Core Web App

How to Implement SignalR in .NET Core Web App

The Intro- Whats SignalR?

SignalR is an open-source library developed by Microsoft that enables real-time communication between servers and clients in web applications.

What’s so special?

Traditional web applications follow a request-response model, where the client requests data, and the server responds. SignalR transforms this paradigm by allowing servers to push updates to clients proactively, facilitating instantaneous data synchronization. Like a real chaaat!

Key Features of SignalR:

  • Real-Time Communication: Supports bidirectional communication, enabling servers and clients to exchange messages with minimal latency.
  • Automatic Protocol Management: Automatically selects the most efficient transport protocol (WebSocket, Server-Sent Events, or Long Polling) based on client and server capabilities.
  • Group Management: Allows the creation and management of groups of connections, facilitating targeted broadcasting of messages to specific user sets.
  • Cross-Platform Support: Compatible with various languages, including JavaScript, .NET, and Java, making it suitable for cross-platform real-time applications.
  • Security: Offers built-in authentication and authorization mechanisms, ensuring secure communication channels protected by encryption and digital signatures, if needed.

Implementing SignalR in .NET Core:

To integrate SignalR into an ASP.NET Core MVC project, follow the below steps:

Prerequisites

  • .NET 8 SDK
  • Visual Studio 2022

1. Install SignalR NuGet Package:

Use the Package Manager Console or NuGet Package Manager to install the SignalR package:

dotnet add package Microsoft.AspNetCore.SignalR

2. Add SignalR Middleware:

In the Program.cs file, incorporate SignalR services and map the SignalR hub:

var builder = WebApplication.CreateBuilder(args);

// Add SignalR services
builder.Services.AddSignalR();

var app = builder.Build();

// Map the SignalR Hub
app.MapHub("/IntertoonsChatHub");

app.Run();

3. Create a Hub:

Define a Chat Hub class that inherits from Hub and implements methods for client-server communication:

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

public class IntertoonsChatHub : Hub
{

public async Task SendMessage(string user, string message)
{

await Clients.All.SendAsync("ReceiveMessage", user, message);
}

}

4. Add Client-Side Scripts:

Include the SignalR JavaScript client library in your view, either via a CDN or by installing it locally:

<!-- Reference SignalR library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.9/signalr.min.js"></script>

5. Create a View for Real-Time Communication:

Develop a simple chat interface in your Razor view:

<div id="messagesList"></div>
<input type="text" id="userInput" placeholder="Enter your name" />
<input type="text" id="messageInput" placeholder="Enter a message" />
<button onclick="sendMessage()">Send</button>

<script>
    const connection = new signalR.HubConnectionBuilder().withUrl("/IntertoonsChatHub").build();

    connection.on("ReceiveMessage", (user, message) => {
        const msg = document.createElement("div");
        msg.textContent = `${user}: ${message}`;
        document.getElementById("messagesList").appendChild(msg);
    });

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

    function sendMessage() {
        const user = document.getElementById("userInput").value;
        const message = document.getElementById("messageInput").value;
        connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
    }
</script>

6. Run the Application:

Launch your application and navigate to the appropriate view to test the real-time chat functionality.

By following these steps, you can implement real-time communication in your .NET Core application using SignalR, enhancing user engagement and interactivity.


Interoons aim at providing electronically intelligent and comprehensive range of digital marketing solutions that exceed customer expectations. We implement revolutionary digital marketing ideas to achieve a common as well as the aggregate growth of the organization. Long-term customer relations and extended support are maintained.

Leave a Reply

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