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