我在 ASP 站点上创建了一个“记住我”选项,客户说他们也希望它在用户字段中显示登录名,即使他们按下“注销”后也是如此。只要我不再使用不同的登录名,它就可以工作。一旦我将值分配给后面代码中的文本框,即使我手动键入新值,也会使用旧值。
示例:
- 我输入用户名/密码(例如 User1),点击“记住我”并成功登录。
- 我注销并重定向回登录页面。在 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 属性不会改变?
最佳答案
问题是您没有在 Page_Load
方法中检查您是否处于回发状态 - 这意味着即使用户在 txtLoginUsername
文本框中添加了其他内容它被 CheckLoginCookie
覆盖。
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;
// Only check the login cookie if we are not dealing with a form submission.
if (!Page.IsPostBack)
{
CheckLoginCookie();
}
}
}
关于c# - 为什么 ASP 文本框有时显示的文本值与屏幕上显示的文本值不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12696303/