简单的记住密码
可以记住用户名和密码,但是如果不选择记住的话,仍然在下次登录的时候显示用户名和密码。存在于客户端的cookie始终存在,删除不了。
<body> <form id="form1" runat="server"> <div style="width: 250px; margin: 20px auto; border: 1px solid green; text-align: right;"> <table style="width: 100%"> <tr> <td> 用户名: </td> <td> <asp:TextBox class="txt" ID="txtUserName" runat="server"></asp:TextBox> </td> </tr> <tr> <td> 密 码: </td> <td> <asp:TextBox class="txt" ID="txtPassword" TextMode="Password" runat="server"></asp:TextBox> </td> </tr> <tr> <td colspan="2"> <asp:CheckBox ID="chkRemember" runat="server" Text="记住用户名和密码" /> </td> </tr> <tr> <td colspan="2"> <asp:Button ID="btnLogin" runat="server" Text="登录" OnClick="btnLogin_Click" /> </td> </tr> </table> </div> </form></body>
public partial class RememberPwd : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { HttpCookie cookie = Request.Cookies["UserInfo"]; if (cookie != null) { this.txtUserName.Text = cookie.Values["uName"]; this.txtPassword.Attributes.Add("value", cookie.Values["uPassword"]); } } } protected void btnLogin_Click(object sender, EventArgs e) { string uName = this.txtUserName.Text.Trim(); string uPassword = this.txtPassword.Text.Trim(); //验证用户名密码,如果通过验证,则根据用户选择决定是否保存密码。 if (IsLogin(uName, this.txtPassword.Text.Trim())) { //获取所提交的请求中包含的Cookie HttpCookie cookie = Request.Cookies["UserInfo"]; #region 创建cookie,保存用户名和密码 //判断用户是否要求保持用户名及密码 if (chkRemember.Checked == true) { //判断是否已经保持过用户名及密码,如果是第一次则创建一个新的cookie if (cookie == null) { //创建一个名为UserInfo的Cookie cookie = new HttpCookie("UserInfo"); //在cookie中添加键值对 cookie.Values.Add("uName", uName); cookie.Values.Add("uPassword", uPassword); //设置Cookie过期时间,两周 cookie.Expires = DateTime.Now.AddDays(14); //保存Cookie Response.Cookies.Add(cookie); } else //如果该cookie存在,则修改cookie的值 { cookie.Values.Set("uName", uName); cookie.Values.Set("uPassword", uPassword); Response.SetCookie(cookie); } } else { if (cookie != null) { //不知道什么原因,就是删不掉,下次登录还存在 Response.Cookies.Remove("UserInfo"); } } #endregion //通过验证后,将用户信息保持到Session中,只要浏览器不关闭,这个Session就有效 User currentUser = new User(uName, this.txtPassword.Text.Trim()); Session["USER"] = currentUser; if (Request.QueryString["FROM"] == null || Request.QueryString["FROM"] == "") { Response.Redirect("Default.aspx"); } else { Response.Redirect(Request.QueryString["FROM"]); } } } private bool IsLogin(string uName, string p) { return true; }}