ASP.NET Core MVC Advanced

Real-time updates with SignalR

SignalR pushes updates from the server to browsers in real time, for chat, notifications, live dashboards and order tracking. This lesson builds a hub, connects from JavaScript, sends to one user or a group, and covers scaling to several servers.

Live order status
  1. StartBrowser connectsJoins group order-42 through the hub
  2. Step 2Kitchen marks readyController updates the database
  3. Step 3IHubContextSends statusChanged to group order-42
  4. Step 4WebSocket pushMessage arrives instantly
  5. EndPage updatesStatus changes without a refresh

How SignalR works

A hub is a class on the server that clients connect to. SignalR picks the best transport, usually WebSockets, falling back to Server-Sent Events or long polling. Both sides can call methods on the other.

Use it when users should see changes without refreshing: new messages, order status, stock levels or progress of a long job.

The hub and setup

C#
[Authorize]
public class OrdersHub : Hub
{
    public async Task WatchOrder(int orderId) =>
        await Groups.AddToGroupAsync(Context.ConnectionId, $"order-{orderId}");
}

builder.Services.AddSignalR();
app.MapHub<OrdersHub>("/hubs/orders");

// Send from anywhere, such as a controller or background service
public class KitchenController(IHubContext<OrdersHub> hub) : Controller
{
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> MarkReady(int orderId)
    {
        // ... update the database ...
        await hub.Clients.Group($"order-{orderId}").SendAsync("statusChanged", orderId, "Ready");
        return RedirectToAction("Index");
    }
}

The browser client

Load the @microsoft/signalr script (from npm or a CDN), connect, and register handlers for server messages.

JavaScript
const connection = new signalR.HubConnectionBuilder()
  .withUrl('/hubs/orders')
  .withAutomaticReconnect()
  .build();

connection.on('statusChanged', (orderId, status) => {
  document.querySelector('#status').textContent = status;   // textContent, not innerHTML
});

await connection.start();
await connection.invoke('WatchOrder', 42);

Good to know

  • Clients.User(userId) sends to every connection of one signed-in user; Clients.All sends to everyone.
  • Hubs are transient: do not store state in hub fields; use groups, a database or a cache.
  • With several servers, add a backplane (Redis) or use Azure SignalR Service so a message reaches clients on every server.
  • Authorize hubs like controllers; validate everything a client sends.

Interview question

How do you send a SignalR message from a controller, outside the hub?

Inject IHubContext<THub> into the controller or service and call Clients.All, Clients.User(id), Clients.Group(name) or Clients.Client(connectionId) with SendAsync and the method name and arguments. Hub instances are short-lived and created per call, so IHubContext is the supported way to push messages from elsewhere in the app.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.