【问题标题】:ASP NET Core SignalR OnDisconnectedAsync not firing with hub [Authorized]ASP NET Core SignalR OnDisconnectedAsync 未使用集线器触发 [已授权]
【发布时间】:2020-05-10 14:00:46
【问题描述】:

.net 核心 2.1

中心代码:

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

}

客户端代码:

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

没有 [Authorize] 一切正常,除了 OnConnectedAsync 中的 Context.UserIdentifier,它是可以解释的,但是......在 Hub 类上使用 [Authorize] 属性,OnConnectedAsync 开始工作并且 OnDisconnected 根本不会触发,包括 30 秒超时(通过默认)。

有什么想法吗?

【问题讨论】:

  • OnConnectedAsync start working and OnDisconnected not fires at all 浏览器控制台标签有错误吗?
  • 关于用户关闭浏览器(或标签页)事件的案例
  • 你是如何解决这个问题的?问题是什么?

标签: asp.net-core signalr asp.net-core-signalr


【解决方案1】:

添加

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

这应该会触发 SignalR Hub 中的 OnDisconnectedAsync

【讨论】:

    【解决方案2】:

    如果您附加了调试器并通过关闭浏览器选项卡来关闭客户端,那么您将永远不会观察到OnDisconnectedAsync 被触发。这是因为 SignalR 检查是否附加了调试器并且不触发某些超时以使调试更容易。如果您通过在客户端上调用 stop 来关闭,那么您应该会看到 OnDisconnectedAsync 被调用。

    【讨论】:

      【解决方案3】:

      为 blazor 实现此代码

      @implements IAsyncDisposable
      

      并粘贴此函数。编码

      public async ValueTask DisposeAsync()
      {
          if (hubConnection is not null)
          {
              await hubConnection.DisposeAsync();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-07
        • 1970-01-01
        • 2017-09-16
        相关资源
        最近更新 更多