好吧,我有一個任務,我必須讓客戶端嘗試輸入密碼3次,如果他沒有在3次輸入正確的密碼,它會將他重定向到另一個頁面,問題是我不知道如何使用會話,我怎麼能像++或什麼。添加到會話號碼
Session["counter"] = 0;
,我試圖做到以下幾點:
Session["counter"]++;
我如何可以檢測如果客戶端嘗試輸入密碼3次? 謝謝
好吧,我有一個任務,我必須讓客戶端嘗試輸入密碼3次,如果他沒有在3次輸入正確的密碼,它會將他重定向到另一個頁面,問題是我不知道如何使用會話,我怎麼能像++或什麼。添加到會話號碼
Session["counter"] = 0;
,我試圖做到以下幾點:
Session["counter"]++;
我如何可以檢測如果客戶端嘗試輸入密碼3次? 謝謝
int counter=1;
Session["counter"]=counter;
當你想更新,讀出的值,並將其轉換爲int,然後增加,救回來
if(Session["counter"]!=null)
{
counter=Convert.ToInt32(Session["counter"]);
}
counter++;
Session["counter"]=counter;
編輯:按照註釋,這是怎麼了你可以檢查計數器的值。我用2種方法來包裝檢查來設置和獲取,甚至可以使用其他人提到的屬性。
private int GetLoginAttempts()
{
int counter=0;
if(Session["counter"]!=null)
{
counter=Convert.ToInt32(Session["counter"]);
}
return counter;
}
private void IncreaseLoginAttempts()
{
if(Session["counter"]!=null)
{
counter=Convert.ToInt32(Session["counter"]);
}
counter++;
Session["counter"]=counter;
}
,當用戶試圖登錄(你按一下按鈕/操作方法),通過在產權包裹它,以便檢查當前值
if(GetLoginAttempts()==3)
{
//This means user already tried 3 times, show him a message !
}
else
{
//Do the login process, If login fails, increase the counter
IncreaseLoginAttempts()
}
試試這個。
int counter = Int32.Parse(Session["counter"].ToString()); //Session["counter"] may be null
Session["counter"] = ++counter;
您可以實現它:
public int PasswordAttempts
{
get
{
if (Session["PasswordAttempts"] == null)
Session["PasswordAttempts"] = 0;
return (int)Session["PasswordAttempts"];
}
set
{
Session["PasswordAttempts"] = value;
}
}
protected void Submit_Click(object sender, EventArgs e)
{
PasswordAttempts++;
}
private Int16 Counter
{
get
{
if (ViewState["Counter"] == null)
return 0;
else
return Convert.ToInt16(ViewState["Counter"]);
}
set
{
Int16 counter = 0;
if (ViewState["Counter"] == null)
counter = 0;
else
counter = Convert.ToInt16(ViewState["Counter"]);
ViewState["Counter"] = counter + 1 + value;
}
}
if(counter == 3)
{
}
非常感謝您的回答,但是如何檢查會話計數器是否爲3?我怎麼能做出這樣的陳述? – idish 2012-04-03 19:13:47
@idish:我更新了您的評論的答案 – Shyju 2012-04-03 19:21:05
我們可以將此代碼縮減爲單個屬性嗎? – Pankaj 2012-04-03 19:22:51