omar wasfi
omar wasfi

Reputation: 567

Signal R - OnDisconnectedAsync(Exception? exception) Function is Not working

I'm working on a chat application on the web using blazor web assemblly

I'm tring to push the states(Online / Offline) of users to each others.

enter image description here

here is the signalRHub

enter image description here

On connected is working fine.

public override Task OnConnectedAsync()

My problem is that OnDisconnectedAsync() not getting hitted by the debuger at all

Even after I close the client(browser) that the server is connected with.

    public override Task OnDisconnectedAsync(Exception? exception)
    {
        var userId = _userManager.GetUserId(Context.User);


        return base.OnDisconnectedAsync(exception);
    }

Upvotes: 2

Views: 1412

Answers (1)

Brian Parker
Brian Parker

Reputation: 14533

You need to configure the middleware for the token on the server for signalr.

services.AddAuthentication().AddIdentityServerJwt();

services.TryAddEnumerable(
    ServiceDescriptor.Singleton
        <IPostConfigureOptions<JwtBearerOptions>,ConfigureJwtBearerOptions>());
public class ConfigureJwtBearerOptions : IPostConfigureOptions<JwtBearerOptions>
{
    public void PostConfigure(string name, JwtBearerOptions options)
    {
        var originalOnMessageReceived = options.Events.OnMessageReceived;
        options.Events.OnMessageReceived = async context =>
        {
            await originalOnMessageReceived(context);

            if (string.IsNullOrEmpty(context.Token))
            {
                var accessToken = context.Request.Query["access_token"];
                var path = context.HttpContext.Request.Path;

                if (!string.IsNullOrEmpty(accessToken) &&
                    path.StartsWithSegments("/hubs"))
                {
                    context.Token = accessToken;
                }
            }
        };
    }
}

NOTE: This assumes your hub endpoint(s) start with "/hubs"

Upvotes: 1

Related Questions