What is "OnConnected" in SignalR?
1 Answer
In SignalR, OnConnected (or more specifically
OnConnectedAsync in modern ASP.NET Core SignalR) is a hub lifecycle method that runs when a client successfully establishes a connection to a hub.
ASP.NET Core SignalR
You typically override OnConnectedAsync in your Hub class:
using Microsoft.AspNetCore.SignalR;
public class ChatHub : Hub
{
public override async Task OnConnectedAsync()
{
string connectionId = Context.ConnectionId;
Console.WriteLine($"Client connected: {connectionId}");
await base.OnConnectedAsync();
}
}
When it is called
The method executes when:
- A client starts a SignalR connection.
- The SignalR handshake completes successfully.
- The connection is registered by the hub.
Common uses
- Logging connection activity
- Tracking online users
- Adding users to groups
- Initializing connection-specific data
- Sending a welcome message
Example:
public override async Task OnConnectedAsync()
{
await Clients.Caller.SendAsync(
"ReceiveMessage",
"Welcome to the chat!");
await base.OnConnectedAsync();
}
Related lifecycle methods
OnConnectedAsync()– called when a client connects.OnDisconnectedAsync(Exception? exception)– called when a client disconnects.- Hub methods (your custom methods) – called when clients invoke server-side actions.
Older SignalR versions
In classic ASP.NET SignalR (pre-Core), the method was named:
public override Task OnConnected()
{
return base.OnConnected();
}
In ASP.NET Core SignalR, it was renamed to:
public override Task OnConnectedAsync()
{
return base.OnConnectedAsync();
}
So if you're working with modern SignalR, OnConnectedAsync() is the method you'll use to execute logic whenever a new client connection is established.