skip to content

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%

answer

  1. ISingleClientProxy, one connection only
  2. Clients.Client(id) or Clients.Caller
  3. InvokeAsync<T> requires a CancellationToken
  4. HubException or IOException on failure
  5. not allowed in OnConnectedAsync

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.

solid answer

~50 s

Client results let the server ask one connection a question and await its answer. In a hub, `Clients.Client(connectionId)` and `Clients.Caller` return an `ISingleClientProxy`; outside, `IHubContext<QuizHub>.Clients.Client(id)` does too. `await proxy.InvokeAsync<int?>("GetDraftAnswer", questionId, cancellationToken)` sends an invocation and the client's `on` handler returns the value; every `InvokeAsync<T>` overload takes a `CancellationToken`, which is my timeout. In a typed hub, an interface method returning `Task<TResult>` does the same. Failure modes: the client throws or has no handler, so the server gets a `HubException`; the connection is unknown or drops mid-wait, giving an `IOException`; the call is made in `OnConnectedAsync`, which throws `InvalidOperationException`; or the target is `All` or a group, which has no single result. In ASP.NET Core 10, awaiting a client result inside a hub method releases that connection's invocation slot, so its next queued call can run.

code

csharp · 21 lines
csharp
public class TimeUpService(IHubContext<QuizHub> hubContext, ILogger<TimeUpService> log)
{
    public async Task<int?> CollectDraftAsync(string connectionId, int questionId)
    {
        using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
        try
        {
            return await hubContext.Clients.Client(connectionId)
                .InvokeAsync<int?>("GetDraftAnswer", questionId, timeout.Token);
        }
        catch (HubException ex)      // client threw or returned nothing
        {
            log.LogWarning(ex, "No draft from {ConnectionId}", connectionId);
            return null;
        }
        catch (IOException)          // connection gone or unknown here
        {
            return null;
        }
    }
}

go deeper

for a junior

Know that the server can ask one client for a value with InvokeAsync<T> and the client returns it from its handler.

for a middle

Explain where ISingleClientProxy comes from (Client, Caller, IHubContext), the required CancellationToken, and the typed-hub Task<TResult> form.

for a senior

Handle the failure modes: HubException, IOException, timeouts, the OnConnectedAsync ban and the released invocation slot, and validate the returned value.

for a principal

Decide when a round trip to a browser belongs in a request path at all, versus a push followed by an explicit client callback with its own timeout.

## What client results are Normally the server only **sends** to clients: `SendAsync` delivers a message and nobody answers. **Client results** turn one send into a request with a reply: the server invokes a handler on one client and awaits the value that handler returns. In the classroom quiz, when time runs out the hub can ask a student's page for the answer currently selected but not yet submitted. ## The server side The method is `InvokeAsync<T>` on **`ISingleClientProxy`**, which you get from: - `Clients.Client(connectionId)` or `Clients.Caller` inside a hub method; - `IHubContext<THub>.Clients.Client(connectionId)` anywhere else. ```csharp using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); int? draft = await hubContext.Clients.Client(connectionId) .InvokeAsync<int?>("GetDraftAnswer", questionId, timeout.Token); ``` Every `InvokeAsync<T>` extension overload has a **`CancellationToken`** parameter with no default value. Use it: without a timeout the server waits until the client answers or disconnects. Some documentation samples omit the token; the shipped API requires it. With a strongly typed hub, declare the method on the client interface with a `Task<TResult>` return type, such as `Task<int?> GetDraftAnswer(int questionId)`, and call `Clients.Client(id).GetDraftAnswer(5)`. ## The client side The client returns the value from the handler it registered for that name; the JavaScript `on` handler may return a value or a promise, and the .NET client's `On` has overloads whose handler returns a result. If no handler is registered, or the handler returns nothing, the client replies with the error "Client didn't provide a result." ## What can go wrong | Situation | What the server sees | |---|---| | client handler throws, or no handler returns a value | `HubException` carrying the client's error | | connection id unknown on this server | `IOException` saying the connection does not exist | | connection drops while you wait | `IOException` saying the connection disconnected | | token cancelled (your timeout) | the await is cancelled | | called in `OnConnectedAsync` | `InvalidOperationException`: client results are not allowed there | | `Task<TResult>` typed method on `All` or a group | `InvalidOperationException`: invoke only works with single clients | ## Interaction with the per-client invocation limit A client's hub calls run one at a time by default (`MaximumParallelInvocationsPerClient` = 1). A hub method that awaits a client result from the **same** client it is serving could deadlock if the slot stayed taken, because the client's completion message must be read before the method can finish. In ASP.NET Core 10 the hub's `SingleClientProxy` releases that connection's invocation slot when the client-result call begins, so the connection keeps reading and the next queued invocation from that client may start while the method waits. Design for that: the waiting method is no longer the only one running for that client. ## When to use it, and when not - Good fits: a short question to one client the server cannot answer itself (a selected value, a confirmation from a kiosk operator), always with a timeout. - Poor fits: anything that should be pushed to many clients, or a long human decision. Tie it to a timer and an explicit hub method the client calls back instead. - Remember the trust boundary: a value returned by a browser is client input and is validated like any other. - In a farm, the client must be reachable from the server making the call; with several servers that depends on the scale-out setup.

  • Why does SignalR refuse client results inside OnConnectedAsync?
    During `OnConnectedAsync` the dispatcher deliberately hands the hub proxies that cannot invoke, so that connection setup can never block waiting on a client reply. Calling `InvokeAsync` there throws `InvalidOperationException` ("Client results inside OnConnectedAsync Hub methods are not allowed."). Send a message instead and let the client call back.

  • Clients.All.InvokeAsync<T> collects one result from every connected client.
  • InvokeAsync<T> needs no CancellationToken because SignalR applies ClientTimeoutInterval to it.
  • A client that has no handler for the name makes the server wait forever.
  • Client results work from OnConnectedAsync to ask a new client for its settings.
  • A value returned through a client result can be trusted like server data.