Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP NET Core SignalR OnDisconnectedAsync not firing with hub [Authorized]

.net core 2.1

Hub code:

[Authorize]    
public class OnlineHub : Hub
{
public override async System.Threading.Tasks.Task OnConnectedAsync()
{
    int userId = Context.UserIdentifier;
    await base.OnConnectedAsync();
}

[AllowAnonymous]
public override async System.Threading.Tasks.Task OnDisconnectedAsync(Exception exception)
{
    var b = Context.ConnectionId;

    await base.OnDisconnectedAsync(exception);

}

Client code:

$(document).ready(() => {
        let token = "token";
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("https://localhost:44343/online", { accessTokenFactory: () => token })
            .configureLogging(signalR.LogLevel.Debug)
            .build();

    connection.start().catch(err => console.error(err.toString()));
    });

Without [Authorize] all works fine, except Context.UserIdentifier in OnConnectedAsync, and it's explainable, but... with [Authorize] attribute on Hub class, OnConnectedAsync start working and OnDisconnected not fires at all, including 30sec timeout (by default).

Any ideas?

like image 245
Юрий Алексеев Avatar asked Sep 06 '25 03:09

Юрий Алексеев


2 Answers

If you have a debugger attached and close the client by closing the browser tab, then you'll never observe OnDisconnectedAsync being fired. This is because SignalR check if a debugger is attached and don't trigger certain timeouts in order to making debugging easier. If you close by calling stop on the client then you should see OnDisconnectedAsync called.

like image 106
ArtemiZ Studio Avatar answered Sep 07 '25 23:09

ArtemiZ Studio


for blazor implement this code

@implements IAsyncDisposable

and paste this func. to code

public async ValueTask DisposeAsync()
{
    if (hubConnection is not null)
    {
        await hubConnection.DisposeAsync();
    }
}
like image 29
etd4gis Avatar answered Sep 08 '25 00:09

etd4gis