2
我在一個ASP網站上創建了一個'記住我'的選項,並且客戶端表示他們也希望它在用戶字段中顯示登錄名,即使他們按下「登出」後也是如此。只要我再也不使用不同的登錄名,它就會工作。一旦我將值分配給後面代碼中的文本框,即使我手動鍵入新值,舊值也是使用的值。爲什麼ASP文本框有時會顯示不同於屏幕上顯示的文本值?
例子:
- 我鍵入用戶名/密碼(如用戶1),單擊 '記住我',併成功登錄。
- 我註銷並重定向回登錄頁面。在page_load事件中,它檢測到存在用戶名(User1)的有效Cookie,並讀取該值並設置文本字段。
- 我將登錄名更改爲其他名稱(例如User2),並且失敗時表示無效的用戶名/密碼。奇怪的。
- 我檢查數據,它使用的是舊文本字段(User1)。我嘗試另一個(例如User3)並按登錄。它失敗了,當我檢查Text屬性時,它仍然說User1,即使在屏幕上它說User3。
無論我做什麼,只要將其設置在代碼隱藏文件中,它都不會更改。就好像一旦文本字段被設置,它就不能被改變。這是不對的,但我沒有很好的解釋。
這裏是有問題的代碼:
頁面加載:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.ServerVariables["AUTH_USER"] != null && !Request.ServerVariables["AUTH_USER"].Equals(""))
{
login.Visible = false;
logout.Visible = true;
btnLogout.Text = "Logout " + Request.ServerVariables["AUTH_USER"];
}
else
{
login.Visible = true;
logout.Visible = false;
CheckLoginCookie();
}
}
代碼設置cookie:
private void SaveLoginCookie()
{
try
{
Response.Cookies["KYSUSR"].Value = txtLoginUsername.Text.Trim();
Response.Cookies["KYSUSR"].Expires = DateTime.Today.AddMonths(6);
}
catch (Exception ex)
{
ExceptionHandling.SendErrorReport(this, ex);
}
}
代碼加載的cookie:
private void CheckLoginCookie()
{
try
{
if (Request.Browser.Cookies)
{
if (Request.Cookies["KYSUSR"] != null && Request.Cookies["KSYFOR"] != null)
{
// logged in as remember
if (Request.Cookies["KYSFOR"].Value == "R")
txtLoginUsername.Text = Request.Cookies["KYSUSR"].Value;
// once set here, the Text property never changes regardless of what is entered into it
}
}
}
catch (Exception ex)
{
ExceptionHandling.SendErrorReport(this, ex);
}
}
執行日誌的代碼在:
protected void btnLogin_Click(object sender, EventArgs e)
{
try
{
String user = txtLoginUsername.Text.Trim();
if (chkSaveUser.Checked)
SaveLoginCookie();
else
{
// set cookie as expired so browser will clear it
Response.Cookies["KYSUSR"].Expires = DateTime.Today.AddDays(-1);
}
if (CheckLogin(user, txtLoginPassword.Text))
{
if (chkSaveUser.Checked)
{
FormsAuthentication.SetAuthCookie(user, true);
}
FormsAuthentication.RedirectFromLoginPage(txtLoginUsername.Text.Trim(), false);
}
}
catch (Exception ex)
{
ExceptionHandling.SendErrorReport(this, ex);
}
}
爲什麼Text屬性不會改變?
是的,你是絕對正確的!我突然意識到這一點,並即將編輯。謝謝你回答如此之快! –
@ user1505422 - 很高興能幫到你! –
完美答案+1 – Abhijeetchindhe