π‘ 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
Post a Comment