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"); } } } }