aspnet webform 記住用戶名密碼

原理:使用cookie記住用戶名密碼,登錄時判斷有無該cookie,有則取出存在cookie中的數據賦值給頁面控件,沒有則直接進入頁面;點擊登錄按鈕時,判斷是否需要記住用戶名密碼,要則新增cookie並返回,不需要則將cookie過期,並返回。

頁面加載:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session.RemoveAll();
            Session.Abandon();

            HttpCookie cookies = Request.Cookies["USER_COOKIE"];
            if (cookies != null)
            {
                this.txtUserID.Value = cookies["UserName"];
                this.txtUserPwd.Attributes.Add("value", cookies["UserPassword"]);
                this.ckRemember.Checked = true;
            }
        }
    }

保存按鈕:

if (this.ckRemember.Checked)
                    {
                        HttpCookie cookie = new HttpCookie("USER_COOKIE");
                        //所有的驗證信息檢測之後,如果用戶選擇的記住密碼,則將用戶名和密碼寫入Cookie裏面保存起來。
                        cookie.Values.Add("UserName", this.txtUserID.Value.Trim());
                        cookie.Values.Add("UserPassword", this.txtUserPwd.Text.Trim());
                        //這裏是設置Cookie的過期時間,這裏設置一個星期的時間,過了一個星期之後狀態保持自動清空。
                        cookie.Expires = System.DateTime.Now.AddDays(30.0);
                        Response.Cookies.Add(cookie);
                    }
                    else
                    {
                        HttpCookie cookie = Request.Cookies["USER_COOKIE"];
                        if (cookie != null)
                        {
                            //如果用戶沒有選擇記住密碼,那麼立即將Cookie裏面的信息情況,並且設置狀態保持立即過期。
                            Response.Cookies["USER_COOKIE"].Expires = DateTime.Now.AddDays(-1);
                        }
                    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章