c# - 从 asp.net 中的不同浏览器选项卡识别登录用户

标签 c# asp.net .net session authentication

我在 asp.net 中有一个带有登录选项的网站。

如果我在两个浏览器选项卡中打开网站并使用相同的用户帐户登录并导航到两个选项卡中的主屏幕,现在我从一个选项卡注销并再次登录同一个选项卡,之后我点击了第二个选项卡,

我如何区分我是从第一个选项卡还是第二个选项卡发送来自代码隐藏的请求?

如果请求来自第二个选项卡,我需要将应用程序导航到登录屏幕。我该怎么做?

在我的主页我添加了这样的逻辑

if (Session["UserID"] == null)
{
   Response.Redirect("Login.aspx");
}

但问题是,当我从第一个选项卡注销并再次登录时,在第二个选项卡刷新后 Session["UserID"] 不为空,所以它会留在那里。但我需要重定向登录页面。如何我能做到吗??

最佳答案

我建议您使用JavaScriptAjax Post 进行重定向。我自己用,觉得靠谱,满足需求。我仍然认为可能有更好的方法来做到这一点。但现在这将完成您的工作。

下面的代码检查选项卡焦点/焦点丢失,并在模糊和焦点上调用 Csharp 代码。

    <script type="text/javascript">
        //divClearMessages
        $(window).on("blur focus", function (e) {
            var prevType = $(this).data("prevType");


            if (prevType != e.type) {   //  script for Please Come Back
                switch (e.type) {
                    case "blur":
                        // Use this if you want to check something after user changes tab
                    case "focus":
                        $.ajax({
                            type: "POST",
                            url: "main.aspx/CheckIfSessionIsNull", // Call here the Csharp method which checks the session and redirect user
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (retValue) {
                                // Do something with the return value from.Net method
                            }
                        });
                        break;
                }
            }

            $(this).data("prevType", e.type);
        })
    </script>

在代码后面添加这个方法:(记得添加[WebMethod]属性)

    [System.Web.Services.WebMethod]
    public static void CheckIfSessionIsNull()
    {
       if (System.Web.HttpContext.Current.Session["UserId"] == null)
          HttpContext.Current.Response.Redirect("Login.aspx");
    }

关于c# - 从 asp.net 中的不同浏览器选项卡识别登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31071540/

相关文章:

c# - 测试父对象是否存在

c# - 有没有一种好的方法来优化迭代次数相乘的嵌套 for 循环?

c# - 依赖注入(inject)无法与具有 Azure Key Vault Value asp.net core 3.0 的 RabbitMQ Service Bus 一起使用

c# - 覆盖 ASP.NET MVC 事件样式表包

asp.net - .aspx 文件必须有页面指令吗?

c# - 使用 LINQ 的 IQueryable 左外连接的扩展方法

c# - 有没有一种简单的方法可以混合两个 System.Drawing.Color 值?

c# - 使用传递给方法的 lambda 表达式会减慢 Entity Framework 查询的速度吗?

c# - 反转或反转正则表达式匹配

asp.net - MVC 升级后如何修复 Chartimg.axd