SignalR adds real-time messaging to ASP.NET Core: the server pushes to browsers the moment something happens, instead of browsers polling. This guide builds a notification feature the way it runs in production: a strongly typed hub, groups per tenant, authenticated connections, and broadcasts from anywhere in your app.
What SignalR gives you
SignalR picks the best transport the browser supports (WebSockets, then Server-Sent Events, then long polling), reconnects automatically, and gives you a simple model: clients call hub methods, and the hub calls methods on clients. You write C# and JavaScript functions; SignalR handles the plumbing.
A strongly typed hub
Define the messages the server can send as an interface. The compiler then checks every call, instead of you passing method names as strings.
public interface INotificationClient
{
Task OrderPlaced(OrderPlacedMessage message);
Task StockLow(string sku, int remaining);
}
public sealed record OrderPlacedMessage(int OrderId, string Customer, decimal Total);[Authorize]
public sealed class NotificationHub : Hub<INotificationClient>
{
public override async Task OnConnectedAsync()
{
var tenant = Context.User?.FindFirst("tenant")?.Value;
if (tenant is not null)
{
await Groups.AddToGroupAsync(Context.ConnectionId, GroupFor(tenant));
}
await base.OnConnectedAsync();
}
public static string GroupFor(string tenant) => $"tenant:{tenant}";
}Register it:
builder.Services.AddSignalR();
app.MapHub<NotificationHub>("/hubs/notifications");Groups instead of connection ids
A user can have several connections (two tabs, a phone), and connection ids change on every reconnect. Don't store them. Send to groups and users instead:
Clients.Group("tenant:42"): everyone in a tenant.Clients.User(userId): all of one user's connections. SignalR finds the user id from theNameIdentifierclaim by default.Clients.All: everyone, rarely what you want in a multi-tenant app.
Group membership is per connection and isn't remembered across reconnects, which is why the example adds the connection in OnConnectedAsync: every new connection joins again.
Send from anywhere with IHubContext
Most messages don't start in the hub. They start when an order is saved, in a service or a background job. Inject IHubContext<THub, TClient>:
public sealed class OrderService(AppDbContext db, IHubContext<NotificationHub, INotificationClient> hub)
{
public async Task PlaceAsync(Order order, CancellationToken ct)
{
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
await hub.Clients.Group(NotificationHub.GroupFor(order.TenantId))
.OrderPlaced(new OrderPlacedMessage(order.Id, order.CustomerName, order.Total));
}
}Send after the save succeeds. A notification for an order that then failed to save is worse than no notification.
Authenticating connections with JWT
Browsers can't send an Authorization header when opening a WebSocket, so the SignalR client sends the token in the query string as access_token. Tell the JWT handler to read it for hub requests only:
.AddJwtBearer(options =>
{
// … token validation as usual …
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var token = context.Request.Query["access_token"];
if (!string.IsNullOrEmpty(token) && context.HttpContext.Request.Path.StartsWithSegments("/hubs"))
{
context.Token = token;
}
return Task.CompletedTask;
},
};
});Tokens in query strings can end up in server logs. Keep access tokens short-lived and make sure your request logging doesn't record query strings for /hubs.
With cookie authentication (a server-rendered app), none of this is needed: the browser sends the cookie with the connection.
The JavaScript client
import * as signalR from "@microsoft/signalr";
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/notifications", { accessTokenFactory: () => auth.getAccessToken() })
.withAutomaticReconnect()
.build();
connection.on("OrderPlaced", message => {
showToast(`New order #${message.orderId} from ${message.customer}`);
});
connection.onreconnected(() => refreshDashboard());
await connection.start();Messages sent while a client was disconnected are not replayed. After onreconnected, reload the data the page shows so nothing is missed.
Keep hub methods thin
Hub methods that clients call should check permissions and hand off to a service, like a controller action:
public async Task MarkRead(int notificationId)
{
var userId = Context.UserIdentifier!;
await notifications.MarkReadAsync(userId, notificationId, Context.ConnectionAborted);
}Never trust a group name or user id sent by the client. Work it out on the server from Context.User.
Scaling out
Connections live in the memory of the server that accepted them. With two servers behind a load balancer, a message sent on server A doesn't reach clients on server B. Two options:
- Redis backplane:
builder.Services.AddSignalR().AddStackExchangeRedis(connectionString);every server publishes through Redis and delivers to its own clients. - Azure SignalR Service: a managed service holds the connections, and your servers only send messages.
Also turn on sticky sessions at the load balancer if clients might fall back to long polling, because each poll must reach the same server.
Wrapping up
A typed hub, groups per tenant, IHubContext for sending from services, and the access_token hook for JWT cover most real-time features. Send after saving, reload data on reconnect, and add a backplane before you add a second server.