SignalR hubs and connections
SignalR hubs and connections
SignalR is an application-level real-time messaging framework. A hub exposes callable methods and sends named messages to connected clients. Its transport negotiation and connection protocol are additional layers beyond a raw WebSocket.
A hub instance is transient; do not store long-lived room state in hub fields. Clients.Caller targets the invoking connection, Clients.All targets all connected clients, and Clients.Group targets members of a named group. A connection is not the same as a person: a user may have multiple connections, and reconnecting may establish a new connection. Automatic reconnect is optional on the .NET client and does not retry the initial StartAsync failure. Ordinary automatic reconnect does not guarantee replay of missed messages; reestablish authorized group membership for a new connection. Optional stateful reconnect, when configured on both ends, can buffer and replay some messages during temporary interruption, but has bounded buffers and is not durable delivery. Use sequence IDs, duplicate detection and a fresh snapshot when continuity is uncertain. Groups are routing aids, not access-control lists; verify authenticated identity and resource permission before joining or publishing protected data. The local examples deliberately expose only fictional public stock, with no authentication configuration; never reuse them as protected hubs. Use TLS, authorization, allowed origins and bounded payloads for deployed services. Await sends and dispose connections. No particular negotiated transport is asserted by these examples.
Baseline: .NET 10 / C# 14. In an approved environment use the complete fixture project, restore only reviewed dependencies from approved sources, then run dotnet build --no-restore and dotnet run --no-build --no-launch-profile. Blazor projects use localhost:5087; stop the server with Ctrl+C. Other examples start a bounded local server and client in one process. No real credentials or external services. Expected results are reasoned, not executed.
Invoke a hub method and receive a result
Create one client and invoke the public synthetic stock query.
using Microsoft.AspNetCore.SignalR;using Microsoft.AspNetCore.SignalR.Client;using System.Net;var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, 0));builder.Services.AddSignalR();await using var app = builder.Build();app.MapHub<StockHub>("/stock");using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(timeout.Token);try { string url = app.Urls.Single() + "/stock";await using var client = new HubConnectionBuilder().WithUrl(url).Build();await client.StartAsync(timeout.Token);Console.WriteLine(await client.InvokeAsync<int>("Available", timeout.Token));} finally { await app.StopAsync(); }public class StockHub : Hub { public int Available() => 4; public Task Notify(string text) => Clients.Caller.SendAsync("Update", text); public Task JoinDemo() => Groups.AddToGroupAsync(Context.ConnectionId, "demo"); public Task SendDemo() => Clients.Group("demo").SendAsync("Update", "Atlas: 4");}Expected result (not executed):
4The invocation crosses the SignalR protocol and returns the hub method result.
Register a callback before publishing
Install a handler first to avoid racing a fast notification.
using Microsoft.AspNetCore.SignalR;using Microsoft.AspNetCore.SignalR.Client;using System.Net;var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, 0));builder.Services.AddSignalR();await using var app = builder.Build();app.MapHub<StockHub>("/stock");using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(timeout.Token);try { string url = app.Urls.Single() + "/stock";await using var client = new HubConnectionBuilder().WithUrl(url).Build();var received = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);using var subscription = client.On<string>("Update", text => { received.TrySetResult(text); });await client.StartAsync(timeout.Token);await client.InvokeAsync("Notify", "Ready", timeout.Token);Console.WriteLine(await received.Task.WaitAsync(timeout.Token));} finally { await app.StopAsync(); }public class StockHub : Hub { public int Available() => 4; public Task Notify(string text) => Clients.Caller.SendAsync("Update", text); public Task JoinDemo() => Groups.AddToGroupAsync(Context.ConnectionId, "demo"); public Task SendDemo() => Clients.Group("demo").SendAsync("Update", "Atlas: 4");}Expected result (not executed):
ReadyThe callback receives a named message sent to the caller. A bounded wait prevents an indefinite hang.
Deliver a message to a demo group
Join a non-sensitive group before publishing a fixed update.
using Microsoft.AspNetCore.SignalR;using Microsoft.AspNetCore.SignalR.Client;using System.Net;var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, 0));builder.Services.AddSignalR();await using var app = builder.Build();app.MapHub<StockHub>("/stock");using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(timeout.Token);try { string url = app.Urls.Single() + "/stock";await using var client = new HubConnectionBuilder().WithUrl(url).Build();var received = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);using var subscription = client.On<string>("Update", text => { received.TrySetResult(text); });await client.StartAsync(timeout.Token);await client.InvokeAsync("JoinDemo", timeout.Token);await client.InvokeAsync("SendDemo", timeout.Token);Console.WriteLine(await received.Task.WaitAsync(timeout.Token));} finally { await app.StopAsync(); }public class StockHub : Hub { public int Available() => 4; public Task Notify(string text) => Clients.Caller.SendAsync("Update", text); public Task JoinDemo() => Groups.AddToGroupAsync(Context.ConnectionId, "demo"); public Task SendDemo() => Clients.Group("demo").SendAsync("Update", "Atlas: 4");}Expected result (not executed):
Atlas: 4The group is a routing target; the example has no private group data or permission claim.
Apply the concept
Design a protected inventory group for a tenant. Specify authorization before joining, permission changes during a connection, and recovery after reconnect.
Use the manual practice and knowledge check to reason about the boundary. Do not deploy these local demonstrations as production services.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
SignalR hubs and connections — knowledge check
Apply the lesson concepts to the following scenarios.
Where should durable room state live?
What does Clients.Caller target?
Are groups an authorization mechanism by themselves?
What should a client do after missing updates?
Does automatic reconnect cover initial StartAsync failures?