我在 asp.net 中有一个带有登录选项的网站。
如果我在两个浏览器选项卡中打开网站并使用相同的用户帐户登录并导航到两个选项卡中的主屏幕,现在我从一个选项卡注销并再次登录同一个选项卡,之后我点击了第二个选项卡,
我如何区分我是从第一个选项卡还是第二个选项卡发送来自代码隐藏的请求?
如果请求来自第二个选项卡,我需要将应用程序导航到登录屏幕。我该怎么做?
在我的主页我添加了这样的逻辑
if (Session["UserID"] == null)
{
Response.Redirect("Login.aspx");
}
但问题是,当我从第一个选项卡注销并再次登录时,在第二个选项卡刷新后 Session["UserID"] 不为空,所以它会留在那里。但我需要重定向登录页面。如何我能做到吗??
最佳答案
我建议您使用JavaScript 和Ajax 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/