![](/img/trans.png)
[英]ASP.NET MVC How to be logout when same user is logged in from different computer
[英]Identifying the logged in user from different browser tab in asp.net
我在asp.net中有一個帶登錄選項的網站。
如果我在兩個瀏覽器選項卡中打開網站並使用相同的用戶帳戶登錄並導航到兩個選項卡中的主屏幕,現在我從一個選項卡注銷並再次登錄到同一選項卡,之后我點擊了第二個選項卡,
我怎么能歧視我從第一個標簽或第二個標簽發送請求后面的代碼?
如果請求來自第二個選項卡,我需要將應用程序導航到登錄屏幕。我該怎么做?
在我的主頁中,我添加了邏輯
if (Session["UserID"] == null)
{
Response.Redirect("Login.aspx");
}
但問題是,當我從第一個選項卡注銷並再次登錄時,在第二個選項卡刷新后,Session [“UserID”]不為空,因此它將保留在那里。但我需要重定向登錄頁面。我可以實現這個??
我建議您使用JavaScript和Ajax Post進行重定向。 我自己使用它,發現它可靠,滿足需要。 我仍然認為可能有更好的方法來做到這一點。 但是現在這將完成你的工作。
下面的代碼檢查選項卡焦點/焦點丟失,並在Blur和焦點上調用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>
在Code后面添加這個方法:(記得添加[WebMethod]
屬性)
[System.Web.Services.WebMethod]
public static void CheckIfSessionIsNull()
{
if (System.Web.HttpContext.Current.Session["UserId"] == null)
HttpContext.Current.Response.Redirect("Login.aspx");
}
基本上您的問題是屬於同一瀏覽器進程的選項卡共享cookie,因此每個選項卡使用相同的會話和會話cookie。
您可以通過關閉MSDN上記錄的會話cookie來解決此問題:
<configuration>
<system.web>
<sessionState cookieless="true"
regenerateExpiredSessionId="true" />
</system.web>
</configuration>
ASP.NET通過自動在頁面的URL中插入唯一的會話ID來維護無cookie會話狀態。
每個新選項卡訪問一個沒有會話ID的URL將啟動一個新會話。
或者,您可以在初始頁面加載事件中生成一些唯一ID,並通過將它們包裝在類中並將該類的實例存儲在會話內的新ID下來存儲/檢索會話變量。
信用和更多信息 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.