在ASP.net Core中使用Signalr强制注销

问题描述

我有一个ASP.Net核心(2.1版)Web应用程序,如果同一用户使用Signalr集线器登录了另一个浏览器(会话),我需要自动强制注销该用户

我在服务器中重写了Onconnected事件,以获取用户列表并从客户端启动连接中心。我没有从Hub Context获取登录用户的详细信息

        public override Task OnConnectedAsync()
        {
            string userName = Context.User.Identity.Name;
            string connectionId = Context.ConnectionId;

            if (CurrentSessionUsers != null && !(CurrentSessionUsers.Exists(x => x.ConnectionId == Context.ConnectionId)))
            {

                CurrentSessionUsers.Add(new CurrentUserSession()
                {
                    UserEmail = Context.User.Claims.Count() > 0 ? Context.User.FindFirst(ClaimIdentifiers.Email.ToString()).Value.ToString() : string.Empty,ConnectionId = Context.ConnectionId,RequestTime = DateTime.Now
                });
            }

            return base.OnConnectedAsync();
        }

来自客户端的代码

            var connection = new signalR.HubConnectionBuilder().withUrl("/signalrhub").build();
            connection.serverTimeoutInMilliseconds = 1000000;
            connection.start().then(function () {

            }).catch(function (err) {
                var errorc = console.error(err.toString());
                return errorc;
            });

我的问题是我没有在Context中获取用户详细信息以及该过程是否正确。

解决方法

我认为,如果您根据用户的连接ID对其进行检查,就可以了。但是,如果用户启动新的浏览器选项卡以启动新的会话。这还将创建一个新的连接ID。

根据您的逻辑,这还将使用户注销。

如果您的要求是让用户仅在一个选项卡中登录,即使用户在同一浏览器中也是如此。这样会很好用。

此外,如果用户关闭所有选项卡并重新调用hub方法,这还将使用户重新登录。