日期:2014-05-17 浏览次数:20577 次
<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");