4

.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?

3
  • OnConnectedAsync start working and OnDisconnected not fires at all are there any error in browser console tab? Commented May 11, 2020 at 6:16
  • My case about event when user closed browser (or tab) Commented May 11, 2020 at 13:41
  • How did you solve this and what was the problem ? Commented Sep 20, 2020 at 22:08

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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();
    }
}

Comments

1

Add

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["JwtIssuer"],
                    ValidAudience = Configuration["JwtAudience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"]))
                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (!string.IsNullOrEmpty(accessToken))
                        {
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    }
                };
            });

This should trigger OnDisconnectedAsync in SignalR Hub

1 Comment

Please provide an explanation on why this is supposed to work.
0

This seems to be very old issue, but i will add some experience about troubleshooting, maybe it'll help someone once. After investigating, why signalR javascript client is not causing OnDisconnectedAsync when using Authorize attribute and HTTP connection for messaging, i found that the DELETE method it sends to server is blocked by CORS policy. So you can look to request responses, and if request is blocked as restricted by CORS, highly likely you need to allow DELETE (and OPTIONS as well) method to your CORS policy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.