2012-11-06 33 views
0

在我的asp.net web應用程序,我想,以防止不同機器或在同一臺PC上相同的用戶名多個用戶登錄在我的Global.asax.as頁面使用Cache.So,如何防止多個用戶使用緩存在asp.net中使用相同的用戶ID登錄?

我把這個行...

protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e) 
    { 
    if (Session["user"] != null) // e.g. this is after an initial logon 
    { 
     string sKey = (string)Session["user"]; 
     string sUser = (string)HttpContext.Current.Cache[sKey]; 
    } 
    } 

,並在我的網頁登錄提交按鈕點擊,

string userName=uName.Text; 
string passWord=pwd.Text; 

string sKey = uName.Text; 
string sUser = Convert.ToString(Cache[sKey]); 
if (sUser == null || sUser == String.Empty) 
      { 
       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"] = TextBox1.Text.Trim(); 

       if (userName.Equals(db_userName) && passWord.Equals(db_password)) 
       { 
        Response.Write("Welcome " + userName); 
       } 
       else 
       { 
        Response.Write("Invalid Login"); 
       } 
      } 
      else 
      { 
       Response.Write("<Marquee><h1><font color=red>ILLEGAL LOGIN ATTEMPT!!!</font></h1></marquee>"); 
       return; 
      } 

但運行我的應用程序時,它是提高會話狀態在Application_PreRequestHandlerExecute事件這種情況下錯誤信息不可用。 ..

我不知道什麼是這裏的問題......所以,請指引我走出這個問題...

或者告訴我另一個好辦法,而不是這一個...

回答

1

會話狀態在初始請求期間不可用,並且在隨後的請求中可能爲空。在會話狀態對象上檢查null,而不僅僅是鍵/值。

if(HttpContext.Current.Session!=null){ 
//Proceed with xyz 
} 

注意,您使用Response.Write here ... while not invalid,is atypical。我會建議重定向到區域。

+0

:感謝您的寶貴suggestion.Could請你告訴我「如何檢查會話狀態對象爲空」? – Saravanan

+1

我在帖子中爲您提供了一個示例。 – Hardrada

+0

非常感謝...剛纔我登錄並用註銷關閉瀏覽器。所以,下次嘗試...但它阻止了我登錄...用戶會話緩存持續多久... – Saravanan

0

使用HTTPContext.Current.Session

+0

:Thanks..Just現在我登錄並用註銷關閉瀏覽器。所以,下次嘗試...但它阻止我登錄...會話持續多久...我意味着SessTimeOut變量的值是什麼... – Saravanan

+1

默認會話超時是20分鐘,如果我記得。 – Hardrada

+0

是的,它是20分鐘,你可以在你的web.config中查看它。如果你沒有它已經去這裏:http://msdn.microsoft.com/en-us/library/h6bb9cz9(vs.80).aspx – SutharMonil

0

使用此事件處理

void Application_AcquireRequestState(object sender, EventArgs e) 
    { 
     if(HttpContext.Current.Session!=null) 
      { 
       // Place your Code here 
      } 
    } 
相關問題