skip to content

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%

answer

  1. one id per connection, assigned by SignalR
  2. override virtual Task methods on Hub
  3. OnConnectedAsync: join default groups
  4. exception null means a clean close
  5. no RemoveFromGroupAsync needed on disconnect

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.

solid answer

~50 s

Every connection gets a unique `Context.ConnectionId`, assigned by SignalR; it identifies that one tab or device and is what group membership and `Clients.Client` use. `Hub` has two virtual methods for the connection's life: `OnConnectedAsync()`, which runs after the connection is registered, so it is the place to add it to default groups or record presence, and `OnDisconnectedAsync(Exception? exception)`, which runs when it ends. If the client closed deliberately, for example with `connection.stop()`, `exception` is `null`; if it ended because of an error such as a network failure, it describes the failure. Each runs on a fresh hub instance, like any invocation. I do not call `RemoveFromGroupAsync` there: SignalR removes the connection from its groups automatically. Client results are not allowed in `OnConnectedAsync`. And a client that vanishes without closing is only noticed after the server's client timeout.

code

csharp · 20 lines
csharp
public class SpaceHub(ILogger<SpaceHub> logger) : Hub
{
    public override async Task OnConnectedAsync()
    {
        // Registered with the lifetime manager already: groups work here.
        await Groups.AddToGroupAsync(Context.ConnectionId, "lobby");
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        if (exception is null)
            logger.LogInformation("{Id} closed cleanly", Context.ConnectionId);
        else
            logger.LogWarning(exception, "{Id} dropped", Context.ConnectionId);

        // No RemoveFromGroupAsync: SignalR removes the connection from its groups.
        await base.OnDisconnectedAsync(exception);
    }
}

go deeper

for a junior

Recall that each connection has a ConnectionId and that you override OnConnectedAsync and OnDisconnectedAsync to react to connects and disconnects.

for a middle

Explain the null versus non-null exception, automatic group cleanup, fresh hub instances and the client-results ban in OnConnectedAsync.

for a senior

Account for silent drops detected only after the client timeout and for crashes that never call OnDisconnectedAsync when designing presence.

for a principal

Keep connection events cheap and idempotent, since connects scale with devices and reconnect storms, not with people.

## The connection id Each connection to a hub gets a **connection id**, a string SignalR generates and exposes as `Context.ConnectionId`. It identifies one client instance (one browser tab, one app), not a person. It is the key for: - group membership: `Groups.AddToGroupAsync(Context.ConnectionId, ...)`; - direct messages: `Clients.Client(connectionId)`; - exclusions: `Clients.AllExcept(...)`, `GroupExcept(...)`. It changes when a client reconnects, since a reconnect is a new connection unless stateful reconnect resumes the old one. ## OnConnectedAsync `Hub.OnConnectedAsync()` is a virtual method that returns `Task`. SignalR calls it once per connection, after the handshake and after the connection has been registered with the hub's lifetime manager, so adding the connection to groups works there. ```csharp public class SpaceHub(ILogger<SpaceHub> logger) : Hub { public override async Task OnConnectedAsync() { await Groups.AddToGroupAsync(Context.ConnectionId, "lobby"); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception? exception) { if (exception is not null) logger.LogInformation(exception, "Connection {Id} dropped", Context.ConnectionId); await base.OnDisconnectedAsync(exception); } } ``` Rules for `OnConnectedAsync`: 1. It runs on a **new hub instance** in its own DI scope, like any hub invocation, so nothing set on fields carries over. 2. **Client results are not allowed** here: calling `InvokeAsync<T>` on `Clients.Caller` throws `InvalidOperationException`. Send a message instead. 3. **An exception thrown from it closes that connection**: SignalR logs it, sends a close message telling the client not to reconnect, and `OnDisconnectedAsync` is not called for that connection. Keep it light and handle expected failures. ## OnDisconnectedAsync and its exception `OnDisconnectedAsync(Exception? exception)` runs when the connection ends: | How it ended | `exception` | |---|---| | client called `connection.stop()` / `StopAsync()` | `null` | | network failure, transport error, server-side abort | the exception describing the failure | Other facts: - **Group cleanup is automatic.** The docs say `RemoveFromGroupAsync` does not need to be called here; after the hub's handler, the lifetime manager removes the connection from every group. - **Timing of silent drops.** A client that disappears without closing (a laptop lid shut, a dead mobile network) is detected only when the server stops hearing from it, by default after the 30-second client timeout. Presence based on disconnect events therefore lags by that much. - **No call on a crash.** If the server process dies, `OnDisconnectedAsync` never runs for its connections. Anything you recorded in `OnConnectedAsync` outside the process must tolerate that. - It also runs on a fresh hub instance. ## Typical uses in a co-working space app - In `OnConnectedAsync`: add the connection to `lobby` and to the member's own company group, and record presence. - In `OnDisconnectedAsync`: update presence and announce departures to the rooms that care. - Not here: heavy database work on every connect, or anything that must happen exactly once per person, since one person may connect from several devices.

  • Why does a member who closed their laptop still show as online for a while?
    The server only learns of a silent drop when it stops receiving messages, including keep-alive pings, from that client. With the default 30-second client timeout, `OnDisconnectedAsync` runs roughly that long after the laptop went away, so presence based on it lags by that much.
  • Is OnConnectedAsync a good place to ask the new client for its local settings with a client result?
    No. SignalR forbids client results in `OnConnectedAsync`; `InvokeAsync` on `Clients.Caller` there throws `InvalidOperationException`. Send a message asking for the settings and let the client call a hub method back, or have the client call a hub method right after `start()`.

  • Context.ConnectionId is the user's id, the same on every device.
  • You must call RemoveFromGroupAsync in OnDisconnectedAsync or groups leak.
  • OnDisconnectedAsync always receives an exception, even on a clean stop.
  • OnConnectedAsync runs once per user, not once per connection.
  • OnDisconnectedAsync is guaranteed to run even if the server process crashes.