2013-01-02 16 views
0

我在哪裏即時防止多個登錄由相同user.If用戶試圖從其他網頁/機登錄(在另一個已經登錄時)的應用程序然後將確認框,詢問他是否需要註銷前一交易日與否,如果他點擊「是」,那麼以前的會議shud登錄off.Im無法註銷前一交易日然而代碼是防止多次登錄,但我怎麼能註銷時先前的會話重定向ñ用戶主頁與存在會話強制註銷中多個登錄的情況下,所有其它會話由相同的用戶

下面是代碼
在loginButton_Click(認證後)

string sKey = loginControl.UserName + loginControl.Password; 
    string sUser = Convert.ToString(Cache[sKey]); 
    if (sUser == null || sUser == String.Empty || sUser == "") 
    { 
     TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0); 
     HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); 
     Session["user"] = loginControl.UserName + loginControl.Password; 
     Response.Redirect("MainPage.aspx"); 
    } 
    else 
    { 
     Response.Write("<script>if(window.confirm('You have already Logged In.Do you want to sign off the previous Session?')){} else{window.location.href='login.aspx'}</script>"); 
     //if part 
     return; 
    } 

在Global.asax中頁面

protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e) 
{ 
    if (System.Web.HttpContext.Current.Session != null) 
    { 
     if (Session["user"] != null) 
     { 
      string sKey = (string)Session["user"]; 
      string sUser = (string)HttpContext.Current.Cache[sKey]; 
     } 
     else 
     { 
      foreach (DictionaryEntry de in HttpContext.Current.Cache) 
      { 
       HttpContext.Current.Cache.Remove((string)de.Key); 
      } 
     } 
    } 
} 
+1

請使用您的IDE和編輯器中的代碼按鈕[格式化您的代碼塊](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks )正確。 –

回答

0

您所使用的目前的做法是有問題的。你保持相同的「鑰匙」(loginControl.UserName + loginControl.Password),以確定您的用戶的會話,而不是每個會話的唯一密鑰(Guid.NewGuid()例如)。
如果你有一個獨特的鍵,你就可以一個會話與另一個區分(例如,如果用戶執行兩次登錄,您就能知道哪個是哪個)

釋:
當用戶登錄後,創建一個新的Guid並將其保存在另一個會話密鑰中(例如,Session["SessionGuid"] = Guid.NewGuid())。
此外要麼放着一本詞典(或創建全局緩存中的每個用戶一個單獨的條目),其中每個用戶id保存唯一的GUID。
因爲在一個會話中,你將有舊的GUID和在新的會話,你將有新的GUID,您可以在各個GUID當前會話有Application_PreRequestHandlerExecute檢查,如果它不匹配 - 斷開用戶。

+0

Blachshma感謝ü這麼多的reply.But如何註銷/清除以前的會話(不是現在),並繼續本login.Im一個新手,所以請指導。 – user1942809

+0

上一個會話與當前Guid不匹配 – Blachshma