Lesson 6 of 8
SignalR - Real-Time Communication
SignalR provides real-time bidirectional communication between server and clients via WebSockets (fallback to SSE, long-polling). Use cases: live dashboards, order tracking, notifications, live chat. Azure SignalR Service handles horizontal scaling across multiple pods.
SignalR Hub - Typed Client Interface
using Microsoft.AspNetCore.SignalR;
// ━━ Typed hub client interface - compile-time safety ━━
public interface IOrderTrackingClient
{
Task OrderStatusUpdated(OrderStatusUpdate update);
Task NotificationReceived(NotificationDto notification);
}
// ━━ Hub - server-side logic ━━
[Authorize]
public class OrderTrackingHub : Hub<IOrderTrackingClient>
{
// Client connects and subscribes to their orders
public async Task SubscribeToOrder(Guid orderId)
{
// Add to SignalR group - all connections in "order:guid" get updates
await Groups.AddToGroupAsync(Context.ConnectionId, $"order:{orderId}");
}
public async Task UnsubscribeFromOrder(Guid orderId) =>
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"order:{orderId}");
public override async Task OnConnectedAsync()
{
var userId = Context.UserIdentifier!; // from JWT sub claim
// Add to user's personal group for direct notifications
await Groups.AddToGroupAsync(Context.ConnectionId, $"user:{userId}");
await base.OnConnectedAsync();
}
}
// ━━ Push from background service/handler ━━
public class OrderStatusChangedHandler(
IHubContext<OrderTrackingHub, IOrderTrackingClient> hubContext)
: INotificationHandler<OrderStatusChangedEvent>
{
public async Task Handle(OrderStatusChangedEvent evt, CancellationToken ct)
{
// Push to all subscribers of this order
await hubContext.Clients
.Group($"order:{evt.OrderId}")
.OrderStatusUpdated(new OrderStatusUpdate(
evt.OrderId, evt.NewStatus, evt.UpdatedAt));
// Also notify the order owner directly
await hubContext.Clients
.User(evt.CustomerId.ToString())
.NotificationReceived(new NotificationDto(
$"Your order status changed to {evt.NewStatus}", DateTime.UtcNow));
}
}
// ━━ Registration ━━
builder.Services.AddSignalR(options =>
{
options.EnableDetailedErrors = builder.Environment.IsDevelopment();
options.KeepAliveInterval = TimeSpan.FromSeconds(15);
options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
});
// For horizontal scaling (multiple pods):
builder.Services.AddSignalR()
.AddStackExchangeRedis(builder.Configuration.GetConnectionString("Redis")!,
options => options.Configuration.ChannelPrefix = "myapp-signalr");
// Map hub:
app.MapHub<OrderTrackingHub>("/hubs/orders");
// ━━ JavaScript client ━━
// const connection = new signalR.HubConnectionBuilder()
// .withUrl("/hubs/orders", { accessTokenFactory: () => getJwt() })
// .withAutomaticReconnect()
// .build();
// connection.on("OrderStatusUpdated", (update) => updateUI(update));
// await connection.start();
// await connection.invoke("SubscribeToOrder", orderId);
record OrderStatusUpdate(Guid OrderId, string Status, DateTime UpdatedAt);
record NotificationDto(string Message, DateTime SentAt);
record OrderStatusChangedEvent(Guid OrderId, Guid CustomerId, string NewStatus, DateTime UpdatedAt) : INotification;
interface INotification { }
interface INotificationHandler<T> { Task Handle(T n, CancellationToken ct); }Tip
Tip
Practice SignalR RealTime Communication in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of SignalR RealTime Communication from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with SignalR RealTime Communication is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?