ASP.NET里面簡單的記住用戶名和密碼


 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using System.Data;
 8 
 9 public partial class _Default : System.Web.UI.Page 
10 {
11     protected void Page_Load(object sender, EventArgs e)
12     {
13         if (!IsPostBack)
14         {
15             //讀取保存的Cookie信息
16             HttpCookie cookies = Request.Cookies["USER_COOKIE"];
17             if (cookies != null)
18             {
19                 //如果Cookie不為空,則將Cookie里面的用戶名和密碼讀取出來賦值給前台的文本框。
20                 this.txtUserName.Text = cookies["UserName"];
21                 this.txtPassword.Attributes.Add("value", cookies["UserPassword"]);
22                 //這里依然把記住密碼的選項給選中。
23                 this.ckbRememberLogin.Checked = true;
24             }
25         }
26     }
27 
28     protected void ASPxButton1_Click(object sender, EventArgs e)
29     {
30         string UserName = txtUserName.Text;
31         string Password = txtPassword.Text;
32         //這個UserTable是數據層獲取的用戶信息。
33         DataTable UserTable = new UserManager().GetUserTable(UserName);
34         //UserTable.Rows.Count>0說明數據庫中有對應的記錄,可以繼續執行。
35         if (UserTable.Rows.Count > 0)
36         {
37             //如果從Cookie里面獲取的密碼和數據庫里面的密碼一致則算是登錄成功
38             if (UserTable.Rows[0]["Password"].ToString() == Password)
39             {               
40                 HttpCookie cookie = new HttpCookie("USER_COOKIE");
41                 if (this.ckbRememberLogin.Checked)
42                 {
43                     //所有的驗證信息檢測之后,如果用戶選擇的記住密碼,則將用戶名和密碼寫入Cookie里面保存起來。
44                     cookie.Values.Add("UserName", this.txtUserName.Text.Trim());
45                     cookie.Values.Add("UserPassword", this.txtPassword.Text.Trim());
46                     //這里是設置Cookie的過期時間,這里設置一個星期的時間,過了一個星期之后狀態保持自動清空。
47                     cookie.Expires = System.DateTime.Now.AddDays(7.0);
48                     HttpContext.Current.Response.Cookies.Add(cookie);
49                 }
50                 else
51                 {
52                     if (cookie["USER_COOKIE"] != null)
53                     {
54                         //如果用戶沒有選擇記住密碼,那么立即將Cookie里面的信息情況,並且設置狀態保持立即過期。
55                         Response.Cookies["USER_COOKIE"].Expires = DateTime.Now;
56                     }
57                 }
58                 //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "<script>alert('" + ex.Message + "')</script>", false);
59 
60                 Response.Redirect("Default.aspx");
61 
62             }
63         }
64     }
65 }

 

除了Cookie當然還有Session等幾種狀態保持,但是個人覺得這種方式還是不錯的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM