loading experience

ASP.NET Core

SignalR: real-time applications with ASP.NET Core

Notifications, chats and dashboards that update themselves: how SignalR works and how to use it well.

SignalR: real-time applications with ASP.NET Core

SignalR lets the server send messages to clients the moment something happens, without the browser constantly polling for updates. It picks the best transport on its own: WebSockets when available, otherwise compatible alternatives.

The server notifies clients the moment something changes.
The server notifies clients the moment something changes.

A hub

public class NotificationsHub : Hub
{
    public async Task JoinGroup(string department)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, department);
    }
}

builder.Services.AddSignalR();
app.MapHub<NotificationsHub>("/hubs/notifications");

Sending from the server, from anywhere

With IHubContext an application service can notify clients even outside the hub, for example when an order changes status:

public class OrderService(IHubContext<NotificationsHub> hub)
{
    public async Task ShippedAsync(Order o)
    {
        // ...update the database...
        await hub.Clients.Group("logistics").SendAsync("orderShipped", o.Id);
    }
}
const conn = new signalR.HubConnectionBuilder()
    .withUrl("/hubs/notifications")
    .withAutomaticReconnect()
    .build();

conn.on("orderShipped", id => showAlert(`Order ${id} shipped`));
await conn.start();
await conn.invoke("JoinGroup", "logistics");

Good practices

  • Authenticate connections and check permissions in every hub method: a client can call any public method.
  • Send small events (identifiers, statuses) and let the client load details with a normal call.
  • With several server instances you need a backplane, such as Redis or Azure SignalR Service, so that messages reach everyone.
  • Plan for reconnection: after an interruption the client must recover what it missed.
Comments (0)

No comments yet.

Leave a comment