skip to content

SignalR Core

SignalR pushes server-to-client messages through hubs over WebSockets, Server-Sent Events or long polling, with groups and backplanes for many servers. Interviewers ask how it behaves at scale.

on this pageshow

explore

questions

28

With the @microsoft/signalr JavaScript client, how do you connect to a hub, handle server pushes with on, and call a hub method?

level: juniorimportance: must knowfreq 66%

answer

  1. new HubConnectionBuilder().withUrl(url)
  2. build() then start(), a promise
  3. register on handlers before start
  4. handler names are case-insensitive in JS
  5. invoke returns a promise of the result

basics

~10 s

Build a connection with new signalR.HubConnectionBuilder().withUrl("/ticker").build(), register handlers with connection.on("PriceChanged", fn) before awaiting connection.start(), then call hub methods with connection.invoke("Subscribe", "MSFT"), which returns a promise of the server's result.

solid answer

~40 s

I create the connection with `new signalR.HubConnectionBuilder().withUrl("/ticker").build()`, optionally adding `withAutomaticReconnect()` and `configureLogging(...)`. Then I register every server-to-client handler with `connection.on("PriceChanged", (symbol, price) => ...)` and only after that `await connection.start()`, so no push arrives before its handler exists; a message for an unregistered name is logged as a warning and dropped. Handler names are matched case-insensitively in the JavaScript client. To call the hub I use `await connection.invoke("Subscribe", "MSFT")`, which resolves with the hub method's return value or rejects with the server's error, or `send` when I do not need an answer. `start()` rejects if the connection is not `Disconnected`, and it is not retried automatically if it fails, so the page catches the error and retries.

code

javascript · 21 lines
javascript
const connection = new signalR.HubConnectionBuilder()
  .withUrl("/ticker")
  .build();

// 1. Handlers first, so no push is missed.
connection.on("PriceChanged", (symbol, price) => {
  document.getElementById(symbol).textContent = price.toFixed(2);
});

// 2. Start, retrying by hand: automatic reconnect does not cover the first start.
async function start() {
  try {
    await connection.start();
    const snapshot = await connection.invoke("Subscribe", "MSFT");
    render(snapshot);
  } catch (err) {
    console.error(err);
    setTimeout(start, 5000);
  }
}
start();

go deeper

for a junior

Recall the four steps: build with HubConnectionBuilder and withUrl, register on handlers, await start, then invoke or send hub methods.

for a middle

Explain why handlers go before start, how names are matched, what invoke and send each resolve with, and when start rejects.

for a senior

Own the connection's lifecycle in a real page: a manual retry for the first start, one shared connection per hub, and stopping it when the owning view goes away.

for a principal

Wrap the connection in one small client module the whole front end uses, so handler names, retry rules and logging stay consistent across features.

## The pieces The browser client is the npm package **`@microsoft/signalr`**, built from the same `dotnet/aspnetcore` tree as the server (a `signalr.js` browser bundle exposes the same API as a global `signalR`). Three objects matter: - **`HubConnectionBuilder`**: a fluent builder for the connection's URL, logging, protocol and reconnect behaviour; - **`HubConnection`**: the connection itself, with `start`, `stop`, `on`, `off`, `invoke`, `send`, `stream` and the `state` and `connectionId` properties; - **`HubConnectionState`**: `Disconnected`, `Connecting`, `Connected`, `Disconnecting` and `Reconnecting`. ## Building and starting a connection For a stock-ticker dashboard whose server maps `app.MapHub<TickerHub>("/ticker")`: ```javascript const connection = new signalR.HubConnectionBuilder() .withUrl("/ticker") .withAutomaticReconnect() .configureLogging(signalR.LogLevel.Information) .build(); connection.on("PriceChanged", (symbol, price) => { document.getElementById(symbol).textContent = price.toFixed(2); }); await connection.start(); const snapshot = await connection.invoke("Subscribe", "MSFT"); ``` The order is the lesson: 1. **Build** the connection; nothing goes over the network yet. 2. **Register handlers** with `on`. The docs call starting after `on` a best practice, so handlers exist before any message is received. If a push arrives for a name with no handler, the client logs a warning ("No client method with the name ... found") and the message is gone. 3. **Start** with `await connection.start()`. It negotiates, picks a transport and completes the hub handshake. It rejects if the connection is not in the `Disconnected` state, and a failed initial start is **not** retried even with `withAutomaticReconnect()`, so wrap it in your own retry. 4. **Call** the hub. ## Receiving: on and off - `connection.on(name, handler)` adds a handler; several handlers can share a name. - The JavaScript client lowercases names on both registration and dispatch, so `on("pricechanged", ...)` still receives `SendAsync("PriceChanged", ...)`. - Arguments arrive in the order the server passed them to `SendAsync`, deserialized from JSON by default, with .NET property names in camelCase. - `connection.off(name)` removes all handlers for that name; `off(name, handler)` removes one. - A handler may return a value; that is how a client answers a server's client-result request. ## Calling the hub | Method | Waits for | Gives you | |---|---|---| | `invoke(name, ...args)` | the server to finish the hub method | a promise of its return value, rejected on a server error | | `send(name, ...args)` | the message to be sent | a promise that resolves once sent, with no result and no server errors | | `stream(name, ...args)` | stream items | an `IStreamResult` you `subscribe` to | The server matches the hub method by name case-insensitively. Calling any of them while the connection is not `Connected` rejects with an error saying data cannot be sent if the connection is not in the `Connected` state. ## Stopping `await connection.stop()` sends a close message on a best-effort basis, moves through `Disconnecting` to `Disconnected` and fires `onclose` callbacks. A single-page app stops the connection when the view that owns it goes away, so a dashboard does not keep a socket open for a page the user left. ## Common mistakes - Registering `on` handlers **after** `await start()` and then wondering why the first prices never appeared. - Assuming `withAutomaticReconnect()` also retries the first `start()`. - Calling `start()` twice, for example from two components; the second call rejects because the connection is no longer `Disconnected`. - Building one connection per widget instead of sharing one connection per hub across the page.

  • What happens to a PriceChanged push that arrives before connection.on("PriceChanged", ...) has run?
    It is lost. The JavaScript client looks up handlers by lowercased name when the invocation arrives; with none registered it logs a warning that no client method with that name was found and drops the message. Registering handlers before `start()` avoids the race.
  • Does the server's TickerHub need SendAsync("pricechanged") to match a JavaScript on("PriceChanged") handler?
    No. The JavaScript client lowercases the name when you call `on` and again when an invocation arrives, so the casing on either side does not matter. That is a JavaScript-client behaviour: the .NET client stores handler names with an ordinal, case-sensitive comparer.

  • Handlers registered with on after start() still receive messages sent before registration.
  • withAutomaticReconnect() also retries a failed first start().
  • connection.send() resolves with the hub method's return value.
  • Calling start() again on a connected HubConnection is a harmless no-op.
  • The JavaScript client matches on() handler names case-sensitively.
open as a page

In ASP.NET Core SignalR, what is a hub, how do you wire it up, and how do Clients.All, Clients.Caller and Clients.Others differ?

level: juniorimportance: must knowfreq 72%

basics

~20 s

A SignalR hub is a class deriving from Hub whose public methods clients call by name. Register it with AddSignalR() and MapHub<QuizHub>("/quiz"). Clients.All reaches every connection, Clients.Caller only the invoking connection, Clients.Others everyone except that caller.

open as a page

Which transports does ASP.NET Core SignalR support, and how does a client end up using one of them?

level: juniorimportance: must knowfreq 58%

basics

~20 s

SignalR supports WebSockets, Server-Sent Events and long polling. By default the client first POSTs to the hub's /negotiate endpoint, gets the transports the server allows, and tries them in that order, falling back to the next one when a transport fails to start.

open as a page

In the SignalR JavaScript and .NET clients, what does withAutomaticReconnect() do by default, and what does a reconnect not give back?

level: middleimportance: must knowfreq 60%

basics

~20 s

SignalR clients do not reconnect unless you call withAutomaticReconnect(). By default it waits 0, 2, 10 and 30 seconds before four attempts, then closes. A successful reconnect is a new connection with a new connection id; pending calls and server-side per-connection state are gone.

open as a page

In the SignalR JavaScript and .NET clients, how do invoke/InvokeAsync and send/SendAsync differ, and when should you pick each?

level: middleimportance: must knowfreq 52%

basics

~20 s

invoke (InvokeAsync in .NET) waits for the hub method to finish and returns its result or error. send (SendAsync) completes once the message is sent, so it returns nothing and never reports server-side failures. Use invoke when the outcome matters.

open as a page

In an ASP.NET Core SignalR hub, how do you put connections into a per-room group and message it, and what are groups not?

level: middleimportance: must knowfreq 60%

basics

~10 s

Call Groups.AddToGroupAsync(Context.ConnectionId, "room-3") from a hub method, then send with Clients.Group("room-3") or Clients.OthersInGroup("room-3"). Groups are named sets of connections, not users: case-sensitive, held in memory, unlistable, cleared on disconnect, and not an authorization mechanism.

open as a page

In ASP.NET Core SignalR, how long does a hub instance live, and why must you not keep state in hub fields or fire-and-forget sends?

level: middleimportance: must knowfreq 58%

basics

~20 s

A SignalR hub instance lives for one invocation: SignalR creates it in a fresh DI scope for each hub method call, OnConnectedAsync or OnDisconnectedAsync, then disposes it. Fields reset every call, and a send started after the method returns hits a disposed hub.

open as a page

Why does ASP.NET Core SignalR need sticky sessions on a server farm, and in which cases can you run without them?

level: middleimportance: must knowfreq 55%

basics

~20 s

A SignalR connection lives only in the process that created it, so all its later requests must reach that process. Sticky sessions are required, Redis backplane included, except on one process, with Azure SignalR Service, or when every client uses WebSockets only and skips negotiation.

open as a page

How does a browser SignalR client send a bearer token to an ASP.NET Core hub, and why must the server read access_token from the query string?

level: middleimportance: must knowfreq 60%

basics

~20 s

The client supplies the token through accessTokenFactory. SignalR sends it in an Authorization header where it can, but browsers cannot set headers on WebSocket or EventSource requests, so it appends access_token to the URL; JwtBearer's OnMessageReceived must copy that value into context.Token for hub paths.

open as a page

Why does a SignalR client stop receiving its room's group messages after an automatic reconnect, and how should the app restore membership?

level: seniorimportance: must knowfreq 52%

basics

~20 s

Groups store connection ids, and a reconnect is a new connection whose new id joined nothing; the old id left its groups on disconnect. Re-add it, ideally in OnConnectedAsync from the user's stored rooms, or by the client calling JoinRoom in onreconnected.

open as a page

For an ASP.NET Core SignalR app, when would you choose Azure SignalR Service with AddAzureSignalR over a Redis backplane, and what changes on your servers?

level: seniorimportance: must knowfreq 45%

basics

~20 s

With a Redis backplane your servers hold every client connection, so you scale by connection count and need sticky sessions. AddAzureSignalR moves the connections to the service: each server keeps a few connections per hub, scales with message load and needs no affinity.

open as a page

In an ASP.NET Core SignalR hub, what are Context.ConnectionId, OnConnectedAsync and OnDisconnectedAsync for, and what does OnDisconnectedAsync's exception tell you?

level: juniorimportance: should knowfreq 48%

basics

~20 s

Context.ConnectionId is the unique id SignalR assigns each connection. Override OnConnectedAsync to run code when a client connects, such as joining groups, and OnDisconnectedAsync(Exception? exception) when it leaves; the exception is null for a deliberate close and set when the connection failed.

open as a page

In ASP.NET Core SignalR, why does Clients.All reach only some clients once the hub runs on several servers, and what fixes it?

level: juniorimportance: should knowfreq 42%

basics

~20 s

Each server's SignalR tracks only its own connections in DefaultHubLifetimeManager, so Clients.All sent on one server skips clients on the others. A Redis backplane (AddStackExchangeRedis) or Azure SignalR Service (AddAzureSignalR) carries every send to every server.

open as a page

In a Blazor WebAssembly component or a .NET app, how do you use the SignalR .NET client, and how should the component clean it up?

level: middleimportance: should knowfreq 40%

basics

~10 s

Reference Microsoft.AspNetCore.SignalR.Client, build with new HubConnectionBuilder().WithUrl(Navigation.ToAbsoluteUri("/ticker")).Build(), register On<T> handlers, then StartAsync. In a component, re-render with InvokeAsync(StateHasChanged) and implement IAsyncDisposable to DisposeAsync the connection.

open as a page

In ASP.NET Core SignalR, how does Clients.User decide which connections belong to a user, and how do you change that with IUserIdProvider?

level: middleimportance: should knowfreq 50%

basics

~20 s

Clients.User(id) reaches every connection whose Context.UserIdentifier equals id. The identifier is computed once per connection by IUserIdProvider; the default reads the ClaimTypes.NameIdentifier claim. Register your own IUserIdProvider as a singleton to use, say, an email claim.

open as a page

In ASP.NET Core 10, how do you push a SignalR message from a Minimal API endpoint or another service, and what does IHubContext<THub> not offer?

level: middleimportance: should knowfreq 55%

basics

~20 s

Inject IHubContext<QuizHub>, a singleton, and call hubContext.Clients.All.SendAsync(...) or another target. It exposes only Clients and Groups: there is no caller outside a hub invocation, so no Caller, Others or Context.ConnectionId, and it cannot invoke hub methods.

open as a page

In ASP.NET Core SignalR, what does deriving a hub from Hub<T> instead of Hub buy you, and what restrictions come with it?

level: middleimportance: should knowfreq 46%

basics

~20 s

Hub<T> takes an interface T describing the client-side methods, so Clients.All.ShowQuestion(q) is compile-time checked instead of SendAsync("ShowQuestion", q). T must be an interface whose methods return Task or Task<T>; SendAsync disappears, and typed hubs do not work under Native AOT.

open as a page

In ASP.NET Core SignalR, what does AddStackExchangeRedis register, and why set ChannelPrefix when several apps share one Redis server?

level: middleimportance: should knowfreq 36%

basics

~20 s

AddStackExchangeRedis registers RedisHubLifetimeManager<THub>, which turns sends into Redis publishes on channels named after the hub's full type name. Two deployments with the same hub on one Redis would hear each other's broadcasts; a distinct Configuration.ChannelPrefix per app keeps them apart.

open as a page

In ASP.NET Core SignalR, what does [Authorize] on a hub class check compared with [Authorize] on a hub method, and when is each evaluated?

level: middleimportance: should knowfreq 48%

basics

~20 s

[Authorize] on the hub class becomes endpoint metadata on the hub's negotiate and connection endpoints, so unauthorized clients are refused before a connection exists. [Authorize] on a method is checked on every invocation against Context.User, the principal captured when the connection started.

open as a page

Your SignalR hub's users sit behind a corporate proxy that blocks WebSockets. What happens, and how do Transports and SkipNegotiation change it?

level: middleimportance: should knowfreq 38%

basics

~20 s

With defaults the WebSocket attempt fails and the client falls back to Server-Sent Events or long polling, so the hub keeps working, just less efficiently. Restricting transports to WebSockets, or skipping negotiation, removes that fallback, and those users cannot connect at all.

open as a page

What does SignalR stateful reconnect add over withAutomaticReconnect(), and what must the server and the client each enable to use it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Stateful reconnect, opt-in since .NET 8, lets a briefly dropped WebSocket reattach to the same connection: both sides buffer and acknowledge messages and replay what was missed, keeping the connection id. Enable AllowStatefulReconnects on MapHub and withStatefulReconnect() (WithStatefulReconnect() in .NET) on the client.

open as a page

How would you track which members are online in an ASP.NET Core SignalR app when users hold several connections and some drop without closing?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Keep a thread-safe map from user id to connection ids, updated in OnConnectedAsync and OnDisconnectedAsync, announcing online on the first connection and offline after the last. Silent drops lag by the client timeout, and crashes leave stale entries.

open as a page

In an ASP.NET Core SignalR hub, how do you stream items to a client with IAsyncEnumerable<T> or ChannelReader<T>, and how does client cancellation reach you?

level: seniorimportance: should knowfreq 32%

basics

~20 s

A SignalR hub method becomes a server-to-client stream when it returns IAsyncEnumerable<T>, ChannelReader<T> or a Task of either. Add a CancellationToken parameter: SignalR cancels it when the client disposes its subscription or disconnects, so the producer stops.

open as a page

Your six-server SignalR commentary hub uses the Redis backplane, and Redis is unreachable for a minute mid-match. Which messages are lost, and what do callers see?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Sends that travel through Redis during the outage are lost: SignalR neither buffers nor replays them. Once the Redis client's few-second retry runs out the publish throws, so hub methods fail and IHubContext callers get exceptions; even local fans miss Clients.All.

open as a page

A SignalR hub on api.example.com serves a browser app on app.example.com. Which CORS policy does the hub need, and why can it not use AllowAnyOrigin?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The SignalR JavaScript client sends credentials by default, so the hub needs a policy with WithOrigins for the app's origin, AllowCredentials, its request headers and GET, POST and DELETE. ASP.NET Core refuses to build a policy combining AllowAnyOrigin with AllowCredentials.

open as a page

In ASP.NET Core SignalR, how do KeepAliveInterval, ClientTimeoutInterval and the client's server timeout fit together, and what else makes the server close a connection?

level: seniorimportance: should knowfreq 44%

basics

~20 s

On WebSockets and Server-Sent Events each side pings when idle (every 15 s) and gives up after 30 s of silence: ClientTimeoutInterval on the server, the server timeout on the client, each at least double the other's keep-alive. An incoming message over 32 KB also closes the connection.

open as a page

How do you switch a SignalR app and its JavaScript and .NET clients to the MessagePack hub protocol, and what changes for the JavaScript client?

level: middleimportance: nice to knowfreq 26%

basics

~10 s

Add the Microsoft.AspNetCore.SignalR.Protocols.MessagePack package and call AddSignalR().AddMessagePackProtocol(); .NET clients call AddMessagePackProtocol() on HubConnectionBuilder, JavaScript clients add @microsoft/signalr-protocol-msgpack and withHubProtocol(new MessagePackHubProtocol()). Messages get smaller, but property names become case-sensitive.

open as a page

In ASP.NET Core SignalR, how does the server request a return value from one client with InvokeAsync<T>, and what can go wrong?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

Call InvokeAsync<T> on an ISingleClientProxy, from Clients.Client(id) or Clients.Caller in a hub or from IHubContext.Clients.Client(id), passing a CancellationToken; the client's on handler returns the value. It fails with HubException if the client errors and IOException if the connection is gone.

open as a page