简体   繁体   中英

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.

在此处输入图像描述

here is the signalRHub

在此处输入图像描述

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

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

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 signalr hub(s) endpoint(s) start with "/hubs"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM