In ASP.NET Core SignalR, what does deriving a hub from Hub<T> instead of Hub buy you, and what restrictions come with it?
answer
- an interface of client methods
- Clients.All.ShowQuestion(q), no strings
- Task or Task<T> return only
- no SendAsync on Hub<T>
- no Native AOT for typed hubs
basics
~20 sHub<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.
solid answer
~50 sWith `Hub<IQuizClient>`, `Clients.All`, `Caller`, `Group(...)` and the rest return an `IQuizClient`, so I write `Clients.Others.ShowQuestion(question)` and the compiler catches a misspelled method or a wrong argument type; with plain `Hub` the method name is a string passed to `SendAsync`, and a typo fails silently on the client. SignalR generates a proxy for the interface at runtime, so it must be an interface with no properties or events, every method returning `Task` or `Task<TResult>`, and no `ref` or `out` parameters. `SendAsync` is gone, the method name sent is the interface method name with any `Async` suffix kept, and `[HubMethodName]` on an interface method renames it. `Task<TResult>` methods are client results and only work on a single connection. The proxy is built with runtime code generation, so since SignalR gained Native AOT support in .NET 9, typed hubs are the documented exception.
code
csharp · 17 linespublic interface IQuizClient
{
Task ShowQuestion(QuizQuestion question);
Task TimeUp(int questionId);
}
public class QuizHub : Hub<IQuizClient>
{
public async Task PublishQuestion(QuizQuestion question)
{
// Typo-proof: a misspelled method name will not compile.
await Clients.Others.ShowQuestion(question);
}
public Task EndQuestion(int questionId) =>
Clients.All.TimeUp(questionId);
}go deeper
Know that Hub<T> uses an interface of client methods so sends are normal method calls the compiler checks.
Explain the interface rules (Task or Task<T>, no properties, events, ref or out), the kept Async suffix, and IHubContext<THub, T> outside the hub.
Weigh typed hubs against Native AOT, where they are not supported, and remember the browser side is still matched by string.
Treat the client interface as a versioned contract between teams; changing a method name breaks deployed browsers even though the server compiles.
## The problem with strings On a plain `Hub`, every push names the client handler with a string: ```csharp await Clients.Others.SendAsync("ShowQuestion", question); ``` If the browser registered `showquestion` that still works (the JavaScript client lowercases handler names), but if someone renames the handler to `DisplayQuestion`, or a .NET client registered `ShowQuestions`, nothing fails at compile time and the message simply finds no handler. Arguments are equally unchecked. ## The typed alternative `Hub<T>` takes an **interface describing the client's methods**: ```csharp public interface IQuizClient { Task ShowQuestion(QuizQuestion question); Task CloseQuestion(int questionId); Task<int?> GetDraftAnswer(int questionId); // a client result } public class QuizHub : Hub<IQuizClient> { public Task PublishQuestion(QuizQuestion question) => Clients.Others.ShowQuestion(question); } ``` `Hub<T>.Clients` is an `IHubCallerClients<T>`, so every target (`All`, `Caller`, `Others`, `Client(id)`, `Group(name)`, `User(id)` and so on) returns a `T`. Calling a method on it serializes an invocation whose target name is the interface method name. `Context` and `Groups` are the same as on `Hub`. ## The rules the interface must follow SignalR builds a proxy class implementing `T` at runtime and validates the interface while doing so. It throws `InvalidOperationException` when: - `T` is not an interface; - the interface declares **properties** or **events**; - a method returns anything other than `Task` or `Task<TResult>`; - a parameter is `ref` or `out`. Other details worth knowing: 1. The **`Async` suffix is not stripped**: an interface method `ShowQuestionAsync` is sent as `ShowQuestionAsync`, so the client must register that exact name. 2. `[HubMethodName("show")]` on an interface method changes the name sent. 3. A trailing `CancellationToken` parameter is not sent to the client; it is passed to the underlying send or invoke. 4. A `Task<TResult>` method is a **client result**: it waits for the client's handler to return a value. It only works on a single-connection target such as `Clients.Caller` or `Clients.Client(id)`; on `All` or a group the proxy throws `InvalidOperationException` ("InvokeAsync only works with Single clients."). 5. `SendAsync` is no longer available on `Clients`; there is no string escape hatch inside the typed hub. ## Outside the hub From endpoints and services, inject **`IHubContext<QuizHub, IQuizClient>`** to keep the typed calls. The untyped `IHubContext<QuizHub>` still works with `SendAsync` and strings. ## Native AOT and trimming .NET 9 added trimming and Native AOT support to SignalR, client and server, with limits: only the JSON protocol (with the System.Text.Json source generator), and **strongly typed hubs are not supported under Native AOT**. Building the proxy needs runtime code generation, so a `PublishAot` app gets build warnings and a runtime exception. Typed hubs are supported with trimming alone. An AOT app goes back to `Hub` with `SendAsync`, copying any `[HubMethodName]` names into the strings. The ASP.NET Core 10 release notes list no SignalR changes, so this still holds on 10. ## When to choose which | Concern | `Hub` | `Hub<T>` | |---|---|---| | Client method name | string in `SendAsync` | interface method | | Compile-time checking | none | names and argument types | | Client results | `Client(id).InvokeAsync<T>(...)` | `Task<TResult>` interface methods | | Native AOT | supported | not supported | The interface checks only the server side: nothing forces the JavaScript client to register matching handlers, so the interface is a contract you still have to honour in the browser code.
- Does Hub<IQuizClient> guarantee the browser actually handles ShowQuestion?No. The interface only checks the server's calls. The JavaScript client registers handlers by string with `connection.on("ShowQuestion", ...)`, so a mismatch there still means the message finds no handler. Keep the names in one place, or test the pair end to end.
- An interface method is declared as Task ShowQuestionAsync(QuizQuestion q). What name does the client have to listen for?`ShowQuestionAsync`. SignalR does not strip the `Async` suffix, so the invocation target is the full method name. Either register that name on the client, drop the suffix from the interface, or put `[HubMethodName("ShowQuestion")]` on the interface method.
- Hub<T> means T is the type of the messages the hub accepts from clients.
- Interface methods on a typed hub client can return void.
- SignalR strips the Async suffix from typed client method names.
- A typed hub can still call Clients.All.SendAsync with a string name.
- Strongly typed hubs are the recommended choice for Native AOT apps.
Assumes ASP.NET Core SignalR 10; .NET 9 added Native AOT support for SignalR but excluded strongly typed hubs, and the 10.0 release notes list no SignalR change to that.