skip to content

Hub Methods & Typed Hubs

A hub is a class whose public methods clients call and whose Clients property calls back into them, with typed hubs and IHubContext for sends from elsewhere. Interviewers probe hub lifetime.

on this pageshow

explore

questions

6

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%

answer

  1. a class deriving from Hub
  2. public methods are what clients call
  3. AddSignalR, then MapHub<THub>(pattern)
  4. SendAsync names the client-side handler
  5. Others = All minus the caller

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.

solid answer

~40 s

A hub is a class that derives from `Microsoft.AspNetCore.SignalR.Hub`. Its public instance methods are the RPC surface clients invoke by name, and its `Clients` property lets those methods call back into handlers the clients registered. In `Program.cs` I call `builder.Services.AddSignalR()` and then `app.MapHub<QuizHub>("/quiz")`; SignalR is part of the shared framework, so no server package is needed. Inside a hub method `Clients.All.SendAsync("ShowQuestion", q)` reaches every connection to that hub, `Clients.Caller` only the connection whose call is running, and `Clients.Others` every connection except the caller. There are finer targets too: `Client(connectionId)`, `AllExcept(...)`, groups and users. `SendAsync` is fire-and-forget toward the client: it finishes once the message is written to each connection, not when a browser has handled it.

code

csharp · 21 lines
csharp
using Microsoft.AspNetCore.SignalR;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();

var app = builder.Build();
app.MapHub<QuizHub>("/quiz");
app.Run();

public record QuizQuestion(int Id, string Text, string[] Choices);

public class QuizHub : Hub
{
    // Teacher publishes; every other connection receives it.
    public Task PublishQuestion(QuizQuestion question) =>
        Clients.Others.SendAsync("ShowQuestion", question);

    // Only the student who answered gets the receipt.
    public Task SubmitAnswer(int questionId, int choice) =>
        Clients.Caller.SendAsync("AnswerReceived", questionId);
}

go deeper

for a junior

Recall the shape: derive from Hub, AddSignalR plus MapHub in Program.cs, and the three targets All, Caller and Others with exactly who each one reaches.

for a middle

Explain that SendAsync names a client handler by string, completes when the message is written rather than handled, and that method lookup is case-insensitive with no overloads.

for a senior

Show you know where the targets stop: no Caller outside a hub invocation, a fresh hub per call, and why every send must be awaited before the method returns.

for a principal

Frame the hub as a thin RPC facade: keep business rules in services the hub calls, so the same logic serves hub calls and IHubContext pushes from elsewhere.

## What a hub is ASP.NET Core SignalR gives a server and its connected clients a **remote procedure call** channel in both directions. The server side of that channel is a **hub**: a class deriving from `Hub` (namespace `Microsoft.AspNetCore.SignalR`). Two directions matter: - **Client to server.** Every `public` instance method declared on the hub can be invoked by a connected client, by method name, with arguments serialized by the hub protocol (JSON by default). - **Server to client.** Inside a hub method, the `Clients` property returns proxies; calling `SendAsync("MethodName", args...)` on one asks the targeted clients to run the handler they registered under that name. A live classroom quiz is a good mental model: the teacher's page calls a hub method to publish the next question, and the hub pushes that question to every student's page. ```csharp using Microsoft.AspNetCore.SignalR; public class QuizHub : Hub { public Task PublishQuestion(QuizQuestion question) => Clients.Others.SendAsync("ShowQuestion", question); public Task SubmitAnswer(int questionId, int choice) => Clients.Caller.SendAsync("AnswerReceived", questionId); } ``` ## Wiring it into Program.cs Two calls are required, and SignalR ships in the ASP.NET Core shared framework, so a web project needs no extra server package: ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddSignalR(); var app = builder.Build(); app.MapHub<QuizHub>("/quiz"); app.Run(); ``` 1. `AddSignalR()` registers the hub infrastructure: the lifetime manager, the JSON hub protocol, the singleton `IHubContext<>` and the default user-id provider. An overload takes an `Action<HubOptions>` for global options. 2. `MapHub<THub>(pattern)` adds an endpoint (plus its `/negotiate` sibling) and returns a `HubEndpointConventionBuilder`, so endpoint conventions can be chained on it. If `AddSignalR` was never called, `MapHub` throws an `InvalidOperationException` telling you to add the required services. A browser then connects with the `@microsoft/signalr` client and calls `connection.invoke("SubmitAnswer", 4, 2)`; how that client is built belongs to the client-side story. ## The Clients targets `Hub.Clients` is an `IHubCallerClients`. The three targets an interviewer asks about first: | Target | Who receives the message | Typical quiz use | |---|---|---| | `Clients.All` | every connection to this hub, caller included | announce the timer starting | | `Clients.Caller` | only the connection that made this call | confirm a student's answer was recorded | | `Clients.Others` | every connection except the caller | teacher publishes a question to the students | Alongside them sit `Clients.Client(connectionId)` and `Clients.Clients(ids)` for specific connections, `AllExcept(ids)` for everyone but a list, and the group and user targets (`Group`, `OthersInGroup`, `User`, `Users`), which are a topic of their own. Each returns a proxy with `SendAsync`; `Caller` and `Client(...)` return an `ISingleClientProxy`, which can also request a value back from that one client. ## What SendAsync does and does not promise - The first argument is the **client handler name**, a plain string. A typo is not a compile error; the message simply finds no handler on the client. - The returned `Task` completes once the message has been written to each targeted connection. It does **not** wait for any client to run its handler or acknowledge it. - Always `await` it. A send started without `await` can outlive the hub instance, which is disposed as soon as the hub method returns. ## Naming rules on the server side - Hub method lookup is **case-insensitive**, so `invoke("submitAnswer")` reaches `SubmitAnswer`. - **Overloads are not supported.** Two public methods with the same name make SignalR throw a `NotSupportedException` ("Overloading is not supported") when it builds the hub's method table. - `[HubMethodName("answer")]` changes the name clients must use. - A client calling a name that does not exist gets an error completion whose message includes `Unknown hub method`. ## Common mistakes - Treating `Clients.All` as "all except me": the caller receives it too, so a teacher page may render its own question twice. - Using `Clients.Caller` from code that is not running inside a hub invocation; outside a hub there is no caller, which is why `IHubContext` exposes no `Caller` or `Others`. - Assuming a hub is a long-lived object per connection. A new hub instance serves every single invocation, so fields do not survive between calls.

  • How would the teacher page receive its own published question as well, without a second call?
    Send with `Clients.All` instead of `Clients.Others`: `All` includes the calling connection, so the teacher's page gets the same `ShowQuestion` message as every student. `Others` deliberately excludes the caller; `AllExcept(ids)` is the general form when more than the caller must be skipped.
  • Why can two public hub methods not share a name with different parameters?
    SignalR resolves an invocation by method name alone, case-insensitively, before it deserializes the arguments. When it builds the hub's method table and finds two public methods with the same name, it throws a `NotSupportedException` saying overloading is not supported. Give each method a distinct name or use `[HubMethodName]` to expose different names.

A hub is a classroom intercom: students press a button that rings a specific desk (a hub method), and the teacher can talk to the whole room (All), answer only the student who buzzed (Caller), or address everyone but that student (Others).

  • Clients.All skips the connection that made the call.
  • SendAsync waits until each browser has run its handler.
  • The hub must be registered with AddSingleton<QuizHub>() for MapHub to work.
  • app.UseWebSockets() is what exposes a SignalR hub endpoint.
  • Hub methods can be overloaded by parameter list like any C# method.
  • One hub instance lives for the whole connection, so fields keep state.
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

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 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

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