I lost all connections in Hub when I'm adding ConnectionId to group

Viewed 74

I'm working on my SignalR Hub.

I want to add Context.ConnectionId to specific group when OnConnectedAsync() was triggered.

When I write something like this:

public override Task OnConnectedAsync()                                                                 
{                                                                                                       
    // succeeded adding ConnectionId to User in my cache                                                              
                                                                                                       
    if (succeeded)                                                                                      
    {                                                                                                   
        await Groups.AddToGroupAsync(Context.ConnectionId, user.Id1);
        await Groups.AddToGroupAsync(Context.ConnectionId, user.Id2);   
    }                                                                  
}                                                                                                       

I lost all my connections on the hub. When I deleted this AddToGroupAsync() part, everything works fine (connections exist but not in groups).

Why is it that when I'm adding ConnectionId using AddToGroupAsync(), I lose all connections in that simple method?

1 Answers

I didnt found a solution for that problem so i will answer here.

While you triggering the method:

await Groups.AddToGroupAsync(Context.ConnectionId, user.Id1);

You need to check, if user.Id1 is not null. When it is it seems like SignalR Hub cant handle it and he deletes the connection from the hub.

Before adding connection id to group just check, if string is not null:

if (user.Id1 != null) // or string.IsNullOrEmpty(user.Id1)
{
    await Groups.AddToGroupAsync(Context.ConnectionId, user.Id1);
}
Related