ASP.NET记住密码

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Data;
 
 public partial class _Default : System.Web.UI.Page 
 {
     protected void Page_Load(object sender, EventArgs e)
     {
         if (!IsPostBack)
         {
             //读取保存的Cookie信息
             HttpCookie cookies = Request.Cookies["USER_COOKIE"];
             if (cookies != null)
             {
                 //如果Cookie不为空,则将Cookie里面的用户名和密码读取出来赋值给前台的文本框。
                 this.txtUserName.Text = cookies["UserName"];
                 this.txtPassword.Attributes.Add("value", cookies["UserPassword"]);
                 //这里依然把记住密码的选项给选中。
                 this.ckbRememberLogin.Checked = true;
             }
         }
     }
 
     protected void ASPxButton1_Click(object sender, EventArgs e)
     {
         string UserName = txtUserName.Text;
         string Password = txtPassword.Text;
         //这个UserTable是数据层获取的用户信息。
         DataTable UserTable = new UserManager().GetUserTable(UserName);
         //UserTable.Rows.Count>0说明数据库中有对应的记录,可以继续执行。
         if (UserTable.Rows.Count > 0)
         {
             //如果从Cookie里面获取的密码和数据库里面的密码一致则算是登录成功
             if (UserTable.Rows[0]["Password"].ToString() == Password)
             {               
                 HttpCookie cookie = new HttpCookie("USER_COOKIE");
                 if (this.ckbRememberLogin.Checked)
                 {
                     //所有的验证信息检测之后,如果用户选择的记住密码,则将用户名和密码写入Cookie里面保存起来。
                     cookie.Values.Add("UserName", this.txtUserName.Text.Trim());
                     cookie.Values.Add("UserPassword", this.txtPassword.Text.Trim());
                     //这里是设置Cookie的过期时间,这里设置一个星期的时间,过了一个星期之后状态保持自动清空。
                     cookie.Expires = System.DateTime.Now.AddDays(7.0);
                     HttpContext.Current.Response.Cookies.Add(cookie);
                 }
                 else
                 {
                     if (cookie["USER_COOKIE"] != null)
                     {
                         //如果用户没有选择记住密码,那么立即将Cookie里面的信息情况,并且设置状态保持立即过期。
                         Response.Cookies["USER_COOKIE"].Expires = DateTime.Now;
                     }
                 }
                 //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "<script>alert('" + ex.Message + "')</script>", false);
 
                 Response.Redirect("Default.aspx");
 
             }
         }
     }
 }
posted @ 2012-09-24 15:36  卡在人物  阅读(300)  评论(0编辑  收藏  举报