SignalR Hub OnDisconnectedAsync 方法在 Blazor 服务器中未命中

SignalR Hub OnDisconnectedAsync Method Does Not Get Hit in Blazor Server

在这里,我试图在我的集线器的 OnDisconnectedAsync 方法中从已连接的 connectedId 列表 UserHandler.ConnectedUser 中删除 ConnectionId
但问题是,当用户从应用程序注销或关闭 window 时,集线器上的 OnDisconnectedAsync 方法不会被命中。


如果对我的代码有任何帮助,我们将不胜感激。谢谢你。

下面是我的hub

public class ChatHub : Hub
{
    public List<string> SendingUserList = new List<string>();
    public async Task SendMessage(string to, string message)
    {
        var senderConnectionId = Context.ConnectionId;
        SendingUserList.Add(to);
        SendingUserList.Add(senderConnectionId);
        foreach (var connectionId in SendingUserList)
        {
            await Clients.Client(connectionId).SendAsync("ReceiveMessage", message);
        }
    }
    public override Task OnConnectedAsync()
    {
        Clients.All.SendAsync("ReciveUser", UserHandler.UserName, Context.ConnectionId);
        return base.OnConnectedAsync();
    }
    public override async Task OnDisconnectedAsync(Exception e)
    {
        UserHandler.ConnectedUser.Remove(Context.ConnectionId));
        await base.OnDisconnectedAsync(e);
    }      
}
public static class UserHandler
{
    public static HashSet<string> ConnectedUser = new HashSet<string>();
    public static string UserName { get; set; }
}



下面是我剩下的代码

    protected override async Task OnInitializedAsync()
    {
        UserHandler.UserName = httpContextAccessor.HttpContext.User.Identity.Name;
        hubConnection = new HubConnectionBuilder()
            .WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
            .Build();
        hubConnection.ServerTimeout = TimeSpan.FromMinutes(60);
        hubConnection.On<string>("ReceiveMessage", BroadcastMessage);
        hubConnection.On<string,string>("ReciveUser", RefreshUserList);

        await hubConnection.StartAsync();

        StateHasChanged();
    }
    private void RefreshUserList(string connectedUserId, string connectionId )
    {
        UserHandler.ConnectedUser.Add(connectionId);
        connectedUserList = UserHandler.ConnectedUser;
        StateHasChanged();
    }
    private void BroadcastMessage(string message)
    {
        var encodedMsg = $"{message}";
        messages.Add(encodedMsg);
        StateHasChanged();
    }
    public async ValueTask DisposeAsync()
    {
        await hubConnection.DisposeAsync();
    }

您需要在 Hub 的使用者(Razor 组件)中实现 IAsyncDisposable 接口,如下所示:

@implements IAsyncDisposable

添加这些方法:

public void Dispose()
    {
       
        hubConnection.DisposeAsync();
    }

    public async ValueTask DisposeAsync()
    {
        await hubConnection.DisposeAsync();
    }

现在,当您关闭客户端页面时,将调用 OnDisconnectedAsync 方法。