2010-05-27 88 views
9

有沒有辦法檢測用戶是否已經登錄了另一個具有相同用戶名的會話,並阻止他再次登錄或發送消息?ASP.NET中每個用戶只限制一個會話

+1

有一個看看這篇文章: http://www.sharepoint4developers.net/en-nz/post/limit-session-account.aspx – 2012-02-27 19:45:02

回答

16

您可以隨時在global.asax中實施事件。

實現的Application_Start()設置一個System.Collections.Dictionary(或在您的偏好)和存儲應用程序[]集合中,當用戶logsin,添加用戶名。從Session_End()中的集合中刪除。請記住在使用集合時使用「鎖定」關鍵字:)

玩得開心!

例子:

[page.aspx] 
public partial class page : System.Web.UI.Page { 
    protected bool Login(string userName) { 
     System.Collections.Generic.List<string> d = Application["UsersLoggedIn"] 
      as System.Collections.Generic.List<string>; 
     if (d != null) { 
      lock (d) { 
       if (d.Contains(userName)) { 
        // User is already logged in!!! 
        return false; 
       } 
       d.Add(userName); 
      } 
     } 
     Session["UserLoggedIn"] = userName; 
     return true; 
    } 

    protected void Logout() { 
     Session.Abandon(); 
    } 
} 

[global.asax] 
<%@ Application Language="C#" %> 
<script RunAt="server"> 
    void Application_Start(object sender, EventArgs e) { 
     Application["UsersLoggedIn"] = new System.Collections.Generic.List<string>(); 
    } 

    void Session_End(object sender, EventArgs e) { 
     // NOTE: you might want to call this from the .Logout() method - aswell -, to speed things up 
     string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty ? (string)Session["UserLoggedIn"]; 
     if (userLoggedIn.Length > 0) { 
      System.Collections.Generic.List<string> d = Application["UsersLoggedIn"] 
       as System.Collections.Generic.List<string>; 
      if (d != null) { 
       lock (d) { 
        d.Remove(userLoggedIn); 
       } 
      } 
     } 
    } 
</script> 
+0

如果您使用會話來控制授權,那是... – 2010-05-27 15:47:09

+0

我試過這個解決方案,但我無法在Session_End上訪問應用程序,因爲我的HttpContext.Current爲空。我怎樣才能訪問它? – Inbal 2013-10-30 15:22:48

+0

@FredrikJohansson:如果用戶關閉瀏覽器而不點擊LogOut,並再次嘗試使用相同的用戶名登錄,則用戶將無法登錄。我們如何解決這個問題? – nightfire001 2015-03-12 13:00:57

3

我當它在用戶登錄設置在一個數據庫中的標誌,他們已登錄。它是代表他們多少次在登錄一個int實現了這個地方。我們允許了兩個。然後在驗證用戶時只檢查一下。

+0

你如何確定用戶註銷?也有連接超時。所以你需要至少有一個例程在某處運行,以減少整數 – citronas 2010-05-27 15:37:24

+0

是的,這是一個問題。我相信我們的javascript運行會話超時一致,它會問你是否想保持登錄狀態,如果沒有答案,那麼它會減少計數。在會話結束事件中也有同樣的事情。我們還有一項工作,在半夜將計數重置爲0。 – nportelli 2010-05-27 15:46:53

0

您可以將用戶的SessionID存儲在數據庫中。在每次登錄時,將唯一用戶名和SessionID組合存儲到數據庫中。在主頁面中,將查詢包括到數據庫中,以檢查當前使用的用戶名的最後一次登錄是否來自同一會話。如果沒有,放棄會話並重定向到登錄頁面。

我發佈的行爲應該註銷第二個用戶。您可以更改Session.Abandon到你想要的行爲

2

您可以通過保持用戶的跟蹤記錄中,在Global.asax中使用Application對象。

在在session_start方法或您的登錄方法,您可以檢查用戶存儲在應用程序對象。

在Session_End中的方法或在您的註銷方法,你需要從應用程序對象中刪除用戶。

+0

我試過這個解決方案,但是我無法在Session_End上訪問應用程序,因爲我的HttpContext.Current爲null。我怎樣才能訪問它? – Inbal 2013-10-30 15:22:29

1

不要將其存儲在數據庫中,如果您不能識別用戶註銷事件(它們可以點擊註銷,關閉選項卡,關閉整個瀏覽器,或者可能只是關閉計算機......)。 使用會話進行相同的檢查。

相關問題