Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

What is SignalR in Dot Net Core MVC

SignalR is a real-time communication library from Microsoft that lets a server instantly push updates to connected clients (like web browsers, mobile apps, or desktop apps).

In simple terms

Instead of a client repeatedly asking the server, “Anything new?”, SignalR allows the server to say, “Hey, here’s new data right now!” — instantly.


What it’s used for

SignalR is commonly used in apps that need live updates, such as:

  • Chat applications (like messaging apps)
  • Live dashboards (stocks, analytics)
  • Online gaming
  • Notifications (alerts, updates)
  • Collaborative tools (shared editing)

How it works (conceptually)

SignalR manages the connection between client and server using the best available method:

  • WebSockets (fastest, if supported)
  • Server-Sent Events
  • Long polling (fallback)

You don’t have to worry about which one—it handles that automatically.


Example scenario

Imagine a chat app:

  • User A sends a message
  • The server receives it
  • SignalR immediately pushes that message to User B (no refresh needed)

Where it fits

SignalR is part of the ASP.NET ecosystem and works especially well with .NET applications, though clients can be written in JavaScript, C#, and more.


Key benefits

  • Real-time communication
  • Handles connection management for you
  • Scales with cloud services
  • Works across platforms

 1. Install SignalR

SignalR is already included in modern ASP.NET Core, but if needed:

dotnet add package Microsoft.AspNetCore.SignalR
Microsoft.AspNetCore.SignalR.Common

⚡ 2. Create a Hub (Server-side)

A Hub is the core class that handles communication.

using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
// Send message to all connected clients
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}

⚙️ 3. Configure in Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSignalR();

var app = builder.Build();

app.MapHub<ChatHub>("/chatHub");

app.Run();

🌐 4. Client-side (JavaScript)

<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>

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

// Receive message from server
connection.on("ReceiveMessage", (user, message) => {
console.log(user + ": " + message);
});

// Start connection
connection.start().then(() => {
console.log("Connected");

// Send message to server
connection.invoke("SendMessage", "Shiva", "Hello SignalR!");
});
</script>

🔁 How this works

  1. Client connects to /chatHub
  2. Client calls SendMessage
  3. Server (Hub) receives it
  4. Server broadcasts via ReceiveMessage
  5. All clients instantly get the message

🎯 Output

Shiva: Hello SignalR!




Latest Version:

ChatHub.cs

using Microsoft.AspNetCore.SignalR; namespace SignalRDemo.Hubs; public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync( "ReceiveMessage", user, message ); } public async Task SendToOthers(string user, string message) { await Clients.Others.SendAsync( "ReceiveMessage", user, message ); } public async Task SendToCaller(string user, string message) { await Clients.Caller.SendAsync( "ReceiveMessage", user, message ); } public override async Task OnConnectedAsync() { Console.WriteLine( $"Client Connected: {Context.ConnectionId}" ); await Clients.All.SendAsync( "UserConnected", Context.ConnectionId ); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync( Exception? exception) { Console.WriteLine( $"Client Disconnected: {Context.ConnectionId}" ); await Clients.All.SendAsync( "UserDisconnected", Context.ConnectionId ); await base.OnDisconnectedAsync(exception); } }

Program.cs

using SignalRDemo.Hubs; var builder = WebApplication.CreateBuilder(args); // Add Controllers builder.Services.AddControllers(); // Add SignalR builder.Services.AddSignalR(); // CORS builder.Services.AddCors(options => { options.AddPolicy("SignalRPolicy", policy => { policy .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() .SetIsOriginAllowed(_ => true); }); }); var app = builder.Build(); // HTTPS app.UseHttpsRedirection(); // Static Files app.UseDefaultFiles(); app.UseStaticFiles(); // CORS app.UseCors("SignalRPolicy"); // Controllers app.MapControllers(); // SignalR Hub app.MapHub<ChatHub>("/chatHub"); app.Run();


index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ASP.NET Core 10 SignalR Chat</title> <style> * { box-sizing: border-box; } body { margin: 0; font-family: Arial, sans-serif; background: #f4f7fb; } .container { width: 90%; max-width: 700px; margin: 50px auto; background: white; padding: 30px; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,.1); } h1 { margin-top: 0; text-align: center; } .status { text-align: center; padding: 10px; margin-bottom: 20px; border-radius: 8px; background: #eee; } .online { background: #d1fae5; color: #065f46; } .offline { background: #fee2e2; color: #991b1b; } input { width: 100%; padding: 12px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 8px; font-size: 16px; } button { width: 100%; padding: 12px; border: 0; border-radius: 8px; background: #2563eb; color: white; font-size: 16px; cursor: pointer; } button:hover { background: #1d4ed8; } #messagesList { list-style: none; padding: 0; margin-top: 20px; } #messagesList li { padding: 12px; margin-bottom: 8px; background: #f1f5f9; border-radius: 8px; } .system { background: #fff7ed !important; color: #9a3412; } </style> </head> <body> <div class="container"> <h1>SignalR Chat</h1> <div id="status" class="status offline"> Connecting... </div> <input type="text" id="userInput" placeholder="Enter your name"> <input type="text" id="messageInput" placeholder="Enter message"> <button id="sendButton"> Send Message </button> <ul id="messagesList"></ul> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/10.0.0/signalr.min.js"> </script> <script> // Create SignalR Connection const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .withAutomaticReconnect() .build(); // Connection Started connection.onreconnecting(() => { setStatus( "Reconnecting...", false ); }); connection.onreconnected(() => { setStatus( "Connected", true ); }); connection.onclose(() => { setStatus( "Disconnected", false ); }); // Receive Message connection.on( "ReceiveMessage", function (user, message) { const li = document.createElement("li"); li.textContent = `${user}: ${message}`; document .getElementById("messagesList") .appendChild(li); } ); // User Connected connection.on( "UserConnected", function (connectionId) { const li = document.createElement("li"); li.classList.add("system"); li.textContent = `User connected: ${connectionId}`; document .getElementById("messagesList") .appendChild(li); } ); // User Disconnected connection.on( "UserDisconnected", function (connectionId) { const li = document.createElement("li"); li.classList.add("system"); li.textContent = `User disconnected: ${connectionId}`; document .getElementById("messagesList") .appendChild(li); } ); // Send Message document .getElementById("sendButton") .addEventListener( "click", sendMessage ); async function sendMessage() { const user = document .getElementById("userInput") .value; const message = document .getElementById("messageInput") .value; if (!user || !message) { alert( "Please enter name and message" ); return; } try { await connection.invoke( "SendMessage", user, message ); document .getElementById("messageInput") .value = ""; } catch (error) { console.error(error); } } // Start Connection async function startConnection() { try { await connection.start(); console.log( "SignalR Connected" ); setStatus( "Connected", true ); } catch (error) { console.error(error); setStatus( "Connection Failed", false ); setTimeout( startConnection, 5000 ); } } // Status function setStatus( message, connected ) { const status = document.getElementById( "status" ); status.textContent = message; if (connected) { status.classList .remove("offline"); status.classList .add("online"); } else { status.classList .remove("online"); status.classList .add("offline"); } } startConnection(); </script> </body> </html>

 


Post a Comment

0 Comments