πŸ“‘ Real-Time Magic with SignalR in ASP.NET Core

 

In a world of instant messaging, live dashboards, and collaborative tools, users expect updates in real-time. That’s where SignalR comes in — a powerful ASP.NET Core library for real-time web functionality.

Whether you’re building a chat app, live notification system, or real-time monitoring dashboard, SignalR has you covered.


🧠 What Is SignalR?

SignalR is an ASP.NET Core library that enables real-time bi-directional communication between server and client.

Unlike traditional request/response models, SignalR pushes updates from the server to the client instantly over persistent connections.


πŸ”„ How SignalR Works

SignalR uses WebSockets when available, and gracefully falls back to Server-Sent Events or Long Polling if needed.

It abstracts the underlying transport mechanism so you can focus on logic, not low-level networking.


πŸš€ When to Use SignalR

  • πŸ’¬ Live chat applications
  • πŸ”” Push notifications
  • πŸ“ˆ Real-time dashboards or graphs
  • πŸ§‘‍🀝‍πŸ§‘ Collaborative tools (whiteboards, docs)
  • πŸ›’ Live order tracking in e-commerce

πŸ›  How to Use SignalR in ASP.NET Core

Step 1: Add SignalR to Your Project

Install the NuGet package:


dotnet add package Microsoft.AspNetCore.SignalR

Step 2: Create a Hub

A Hub is a class that handles communication between client and server.

csharp

public class ChatHub : Hub

{

    public async Task SendMessage(string user, string message)

    {

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

    }

}

Step 3: Configure SignalR in Program.cs

csharp

var builder = WebApplication.CreateBuilder(args);

 

builder.Services.AddSignalR();

builder.Services.AddControllersWithViews();

 

var app = builder.Build();

 

app.UseRouting();

app.UseEndpoints(endpoints =>

{

    endpoints.MapControllers();

    endpoints.MapHub<ChatHub>("/chathub");

});


🌐 Client-Side: HTML + JavaScript Example

html

<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@latest/dist/browser/signalr.min.js"></script>

 

<script>

    const connection = new signalR.HubConnectionBuilder()

        .withUrl("/chathub")

        .build();

 

    connection.on("ReceiveMessage", (user, message) => {

        const msg = document.createElement("div");

        msg.textContent = `${user}: ${message}`;

        document.getElementById("messages").appendChild(msg);

    });

 

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

 

    document.getElementById("sendBtn").addEventListener("click", () => {

        const user = document.getElementById("userInput").value;

        const message = document.getElementById("messageInput").value;

        connection.invoke("SendMessage", user, message);

    });

</script>


⚙️ Real-Time with Blazor

SignalR integrates perfectly with Blazor Server for real-time web UIs using C# on both front-end and back-end.

razor

@inject IHubContext<ChatHub> HubContext

 

<button @onclick="SendNotification">Notify</button>

 

@code {

    async Task SendNotification()

    {

        await HubContext.Clients.All.SendAsync("ReceiveMessage", "System", "Blazor says hi!");

    }

}


πŸ§ͺ Advanced Features

  • Groups: Broadcast messages to specific groups

csharp

await Groups.AddToGroupAsync(Context.ConnectionId, "Admins");

await Clients.Group("Admins").SendAsync("ReceiveMessage", "Admin group only");

  • User-specific messaging

csharp

await Clients.User(userId).SendAsync("ReceiveMessage", "Private message");

  • Connection Events: Override OnConnectedAsync and OnDisconnectedAsync in the Hub to track users

πŸ” SignalR and Authentication

SignalR supports:

  • Cookie Authentication
  • JWT Bearer Tokens

For example, to use JWT:

javascript

const connection = new signalR.HubConnectionBuilder()

    .withUrl("/chathub", {

        accessTokenFactory: () => localStorage.getItem("token")

    })

    .build();


πŸ“¦ Hosting SignalR

SignalR works in:

  • ASP.NET Core (self-hosted)
  • Azure SignalR Service (for scalable cloud hosting)
  • Blazor Server

🧠 Summary

Feature

SignalR Capability

Real-time messaging

Push from server to client instantly

Multiple clients

Broadcast to all, some, or single client

Transport fallback

WebSockets > SSE > Long Polling

Language support

JavaScript, .NET, Java, Python clients


🧰 Tools & Resources

 

Comments

Popular posts from this blog

Scrutor the built-in Dependency Injection (DI)

πŸ§… Understanding the Onion Architecture: A Clean Approach to Building Scalable Applications

πŸ”Œ Extension Methods in C#: Power Up Your Code Without Modifying It

Understanding Dependency Injection: A Modern Guide for Developers

🌐 CORS in .NET Explained: Solving the Cross-Origin Problem Like a Pro

Ensuring Data Integrity: The Backbone of Reliable Systems

πŸ” JWT (JSON Web Token) Explained: Secure Your APIs the Modern Way

πŸ”— SQL JOINs Explained: Mastering Table Relationships

πŸ—‚️ DROP vs DELETE vs TRUNCATE in SQL: What’s the Difference?

πŸ›‘️ SIEM Logs Explained: How to Build Secure and Auditable .NET Apps