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?
answer
- Groups.AddToGroupAsync(Context.ConnectionId, name)
- Clients.Group, OthersInGroup, GroupExcept
- created on first add, case-sensitive
- in memory, per connection, no member list
- not a security boundary
basics
~10 sCall 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 sA 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 linespublic 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
Recall AddToGroupAsync and RemoveFromGroupAsync with Context.ConnectionId, and Clients.Group to send to everyone in a room.
Explain that groups hold connection ids, are created on first add, are case-sensitive, cannot be listed, and are cleaned up on disconnect.
Treat groups as routing, not security: authorize before adding, remove on revocation, and keep your own roster when the product needs one.
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.