skip to content

Users, Groups & Connections

SignalR addresses clients by connection id, user and group: OnConnectedAsync, Groups.AddToGroupAsync and IUserIdProvider decide who gets a message. Interviewers ask why groups vanish on reconnect.

on this pageshow

explore

questions

5

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%

answer

  1. Groups.AddToGroupAsync(Context.ConnectionId, name)
  2. Clients.Group, OthersInGroup, GroupExcept
  3. created on first add, case-sensitive
  4. in memory, per connection, no member list
  5. not a security boundary

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.

solid answer

~40 s

A group is a named set of **connection ids**. In a hub method I call `await Groups.AddToGroupAsync(Context.ConnectionId, $"room-{roomId}")`, and `RemoveFromGroupAsync` when the member leaves; the group exists as soon as it has a member, adding twice is harmless, and one connection can be in many groups. To send I use `Clients.Group(name)`, `Clients.OthersInGroup(name)` to skip the sender, `GroupExcept(name, ids)` or `Groups(names)`. What groups are not: they are not persisted (memory only, lost on restart), not listable (there is no API to enumerate or count members), not user-based (each tab or device must join separately), not kept across a reconnect (the new connection id must rejoin), and not security: the docs say so explicitly, so I authorize before adding and remove a member whose access is revoked. Group names are case-sensitive.

code

csharp · 16 lines
csharp
public class SpaceHub(RoomAccess access) : Hub
{
    public async Task JoinRoom(int roomId)
    {
        // Groups are not authorization: check first.
        if (!await access.CanEnterAsync(Context.UserIdentifier, roomId))
            throw new HubException("You are not booked into this room.");

        var group = $"room-{roomId}";            // names are case-sensitive
        await Groups.AddToGroupAsync(Context.ConnectionId, group);
        await Clients.OthersInGroup(group).SendAsync("MemberJoined", Context.UserIdentifier);
    }

    public Task Say(int roomId, string text) =>
        Clients.Group($"room-{roomId}").SendAsync("Message", Context.UserIdentifier, text);
}

go deeper

for a junior

Recall AddToGroupAsync and RemoveFromGroupAsync with Context.ConnectionId, and Clients.Group to send to everyone in a room.

for a middle

Explain that groups hold connection ids, are created on first add, are case-sensitive, cannot be listed, and are cleaned up on disconnect.

for a senior

Treat groups as routing, not security: authorize before adding, remove on revocation, and keep your own roster when the product needs one.

for a principal

Choose group naming and roster storage early, since restarts, multiple servers and reconnects all erase in-memory membership.

## What a group is In ASP.NET Core SignalR a **group** is a name mapped to a set of **connections**. Nothing has to be declared up front: the first `AddToGroupAsync` for a name creates it. Groups are the tool for "everyone in this room": in a co-working space app, each meeting room or desk zone gets a chat group such as `room-3`. ## Joining and leaving The hub's `Groups` property is an `IGroupManager` with two methods, both keyed by **connection id**: ```csharp public class SpaceHub(RoomAccess access) : Hub { public async Task JoinRoom(int roomId) { if (!await access.CanEnterAsync(Context.UserIdentifier, roomId)) throw new HubException("You are not booked into this room."); await Groups.AddToGroupAsync(Context.ConnectionId, $"room-{roomId}"); await Clients.OthersInGroup($"room-{roomId}") .SendAsync("MemberJoined", Context.UserIdentifier); } public Task LeaveRoom(int roomId) => Groups.RemoveFromGroupAsync(Context.ConnectionId, $"room-{roomId}"); public Task Say(int roomId, string text) => Clients.Group($"room-{roomId}").SendAsync("Message", Context.UserIdentifier, text); } ``` Behaviour worth knowing, from the default in-memory lifetime manager: - Adding a connection that is already a member is a no-op; no exception is thrown. - Adding or removing a connection id this server does not know is silently ignored. - A connection can belong to any number of groups. - When a connection ends, it is removed from all its groups automatically, so `OnDisconnectedAsync` does not need to call `RemoveFromGroupAsync`. - **Group names are case-sensitive**: `Room-3` and `room-3` are different groups. ## Sending to groups | Target | Reaches | |---|---| | `Clients.Group(name)` | every connection in the group, sender included | | `Clients.OthersInGroup(name)` | the group minus the calling connection (inside a hub only) | | `Clients.GroupExcept(name, ids)` | the group minus the listed connection ids | | `Clients.Groups(names)` | the union of several groups | Outside a hub, an injected hub context exposes the same `Group`, `GroupExcept` and `Groups` targets and its own `Groups` manager, but no `OthersInGroup`, since there is no caller. ## What groups are not 1. **Not persisted.** Membership is held in memory by the hub lifetime manager; a server restart empties every group. 2. **Not enumerable.** There is no API to list or count the members of a group. The docs give the reason: that information is not available once the app is scaled to several servers. If you need a roster, keep it yourself. 3. **Not user-based.** A user with a laptop and a phone has two connections; each must be added. Sending to a person regardless of rooms is what `Clients.User` is for. 4. **Not kept across reconnects.** A client that reconnects gets a new connection id and must be added again. 5. **Not security.** The docs are explicit that groups are not a security feature. Membership does not expire or get revoked with a user's claims; if access is withdrawn, the app must remove the connection itself. Authorize in the hub method that adds to the group. ## Design tips - Build group names from validated ids (`room-{roomId}`), never from free text a client chose. - Keep the room roster, if the UI needs one, in your own store and update it next to `AddToGroupAsync` and `RemoveFromGroupAsync`. - On several servers, group sends reach other servers only through a backplane or the Azure SignalR Service; that is a scale-out concern rather than a group API one.

  • The UI needs a list of who is in room 3. Which SignalR API returns it?
    None. SignalR offers no way to enumerate or count group members, because with several servers no single server knows the full membership. Keep your own roster, keyed by room, updated where you call `AddToGroupAsync`, `RemoveFromGroupAsync` and in `OnDisconnectedAsync`, in a store shared by all servers if there are several.
  • A member's booking is cancelled while connected. What happens to their room messages?
    They keep arriving. Group membership has no link to the user's claims or bookings, and the docs state groups are not a security feature. The app must call `RemoveFromGroupAsync` for each of that user's connections, for example from the cancellation workflow through an injected hub context, and refuse later `JoinRoom` calls.

A SignalR group is a meeting room's intercom channel: whoever is plugged in at the moment hears announcements, the panel cannot print a list of who is plugged in, and plugging in does not prove you booked the room.

  • You must create a SignalR group before adding connections to it.
  • Adding a connection to a group it is already in throws an exception.
  • Group names are case-insensitive, so Room-3 and room-3 are one group.
  • Groups.AddToGroupAsync takes a user id, so all of a user's devices join at once.
  • A group survives a server restart because SignalR persists membership.
  • Being in a group proves the connection is authorized for that room.
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

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

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