在ASP.NET Web Forms中,我们可以使用以下步骤实现“记住我”功能。
protected void btnLogin_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(txtUsername.Text, txtPassword.Text))
{
if (chkRememberMe.Checked)
{
HttpCookie cookie = new HttpCookie("myAppCookie");
cookie.Values.Add("username", txtUsername.Text.Trim());
cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);
}
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, false);
}
}
protected void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
{
if (Request.Cookies["myAppCookie"] != null)
{
HttpCookie cookie = Request.Cookies["myAppCookie"];
string username = cookie.Values["username"];
if (!string.IsNullOrEmpty(username))
{
MembershipUser user = Membership.GetUser(username);
if (user != null)
{
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
user.UserName,
DateTime.Now,
DateTime.Now.AddDays(30),
true,
user.UserId.ToString());
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.Cookies.Add(cookie);
args.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), new string[] { });
}
}
}
}
通过这些步骤,我们可以在ASP.NET Web Forms中实现“记