---
title: "How can you handle user connection and disconnection events in SignalR?"  
description: "How can you handle user connection and disconnection events in SignalR?"  
author: "ICSM Computer"  
published: 2025-05-22  
updated: 2025-05-22  
canonical: https://www.mindstick.com/interview/34155/how-can-you-handle-user-connection-and-disconnection-events-in-signalr  
category: "c#"  
tags: ["c#", "signalr"]  
reading_time: 3 minutes  

---

# How can you handle user connection and disconnection events in SignalR?

In **SignalR**, you can handle user connection and disconnection events by **overriding** the virtual methods `OnConnectedAsync` and `OnDisconnectedAsync` in your `Hub` class.

## Basic Implementation

```cs
public class ChatHub : Hub
{
    // Called when a new client connects
    public override async Task OnConnectedAsync()
    {
        string connectionId = Context.ConnectionId;
        string userId = Context.UserIdentifier;

        Console.WriteLine($"User connected. UserId: {userId}, ConnectionId: {connectionId}");

        // Optionally store user-connection mapping
        // Notify others or update UI

        await base.OnConnectedAsync();
    }

    // Called when a client disconnects
    public override async Task OnDisconnectedAsync(Exception exception)
    {
        string connectionId = Context.ConnectionId;
        string userId = Context.UserIdentifier;

        Console.WriteLine($"User disconnected. UserId: {userId}, ConnectionId: {connectionId}");

        // Clean up user-connection mapping
        // Notify others or update UI

        await base.OnDisconnectedAsync(exception);
    }
}
```

## Notes

### 1. User Identification

1. `Context.ConnectionId`: Unique for each connection.
2. `Context.UserIdentifier`: Set automatically if authentication is configured.
3. `Context.User`: Full `ClaimsPrincipal` for the user.

To customize `UserIdentifier`, use a custom `IUserIdProvider`:

```cs
public class CustomUserIdProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        // Return a custom ID, e.g., username from claims
        return connection.User?.FindFirst("sub")?.Value;
    }
}
```

Register it:

```cs
services.AddSingleton<IUserIdProvider, CustomUserIdProvider>();
```

### 2. Common Use Cases

1. Tracking online/offline status
2. Managing user groups
3. Cleaning up resources or subscriptions
4. Broadcasting status changes (e.g., “User X has joined”)

## Example: Notifying Others

```cs
public override async Task OnConnectedAsync()
{
    await Clients.Others.SendAsync("UserConnected", Context.UserIdentifier);
    await base.OnConnectedAsync();
}

public override async Task OnDisconnectedAsync(Exception exception)
{
    await Clients.Others.SendAsync("UserDisconnected", Context.UserIdentifier);
    await base.OnDisconnectedAsync(exception);
}
```

## Answers

### Answer by ICSM Computer

In **SignalR**, you can handle user connection and disconnection events by **overriding** the virtual methods `OnConnectedAsync` and `OnDisconnectedAsync` in your `Hub` class.

## Basic Implementation

```cs
public class ChatHub : Hub
{
    // Called when a new client connects
    public override async Task OnConnectedAsync()
    {
        string connectionId = Context.ConnectionId;
        string userId = Context.UserIdentifier;

        Console.WriteLine($"User connected. UserId: {userId}, ConnectionId: {connectionId}");

        // Optionally store user-connection mapping
        // Notify others or update UI

        await base.OnConnectedAsync();
    }

    // Called when a client disconnects
    public override async Task OnDisconnectedAsync(Exception exception)
    {
        string connectionId = Context.ConnectionId;
        string userId = Context.UserIdentifier;

        Console.WriteLine($"User disconnected. UserId: {userId}, ConnectionId: {connectionId}");

        // Clean up user-connection mapping
        // Notify others or update UI

        await base.OnDisconnectedAsync(exception);
    }
}
```

## Notes

### 1. User Identification

1. `Context.ConnectionId`: Unique for each connection.
2. `Context.UserIdentifier`: Set automatically if authentication is configured.
3. `Context.User`: Full `ClaimsPrincipal` for the user.

To customize `UserIdentifier`, use a custom `IUserIdProvider`:

```cs
public class CustomUserIdProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        // Return a custom ID, e.g., username from claims
        return connection.User?.FindFirst("sub")?.Value;
    }
}
```

Register it:

```cs
services.AddSingleton<IUserIdProvider, CustomUserIdProvider>();
```

### 2. Common Use Cases

1. Tracking online/offline status
2. Managing user groups
3. Cleaning up resources or subscriptions
4. Broadcasting status changes (e.g., “User X has joined”)

## Example: Notifying Others

```cs
public override async Task OnConnectedAsync()
{
    await Clients.Others.SendAsync("UserConnected", Context.UserIdentifier);
    await base.OnConnectedAsync();
}

public override async Task OnDisconnectedAsync(Exception exception)
{
    await Clients.Others.SendAsync("UserDisconnected", Context.UserIdentifier);
    await base.OnDisconnectedAsync(exception);
}
```


---

Original Source: https://www.mindstick.com/interview/34155/how-can-you-handle-user-connection-and-disconnection-events-in-signalr

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
