asp.net 使用cookie完成記住密碼自動登入

來源:互聯網
上載者:User

      //------------------------------登入頁面----------------------------

 代碼如下 複製代碼


        string username = this.txtUserName.Text;//使用者名稱
        string password = this.txtPassword.Text;//密碼

        if (UserManager.LoginValidate(username, password) && this.ckState.Checked == true)//判斷登入名稱和密碼是否正確和是否選擇了記住使用者名稱和密碼的複選框
        {
           //判斷用戶端瀏覽器是否存在該Cookie 存在就先清除

            if (Request.Cookies["username"] != null && Request.Cookies["password"] != null)
            {
                Response.Cookies["username"].Expires = System.DateTime.Now.AddSeconds(-1);//Expires到期時間
                Response.Cookies["password"].Expires = System.DateTime.Now.AddSeconds(-1);
            }
            else
            {
                 //向用戶端瀏覽器加入Cookie (使用者名稱和密碼 最好是使用MD5加密)
                HttpCookie hcUserName1 = new HttpCookie("username");
                hcUserName1.Expires = System.DateTime.Now.AddDays(7);
                hcUserName1.Value = username;
                HttpCookie hcPassword1 = new HttpCookie("password");
                hcPassword1.Expires = System.DateTime.Now.AddDays(7);
                hcPassword1.Value = password;
                Response.Cookies.Add(hcUserName1);
                Response.Cookies.Add(hcPassword1);
            }
}


           


   //------------------------轉到登入後的頁面(有母板頁寫母板頁最好)------------------------

 代碼如下 複製代碼
              if (Request.Cookies["username"] != null && Request.Cookies["password"] != null)
                {
                    //使用者曾登入
                
                    username = Request.Cookies["username"].Value.ToString();  //讀取Cookie
                    password = Request.Cookies["password"].Value.ToString();//判斷Cookie讀取出來的使用者名稱和密碼是否能正確登入
                    if (UserManager.LoginValidate(username, password))
                    {
                      //登入後的代碼
             }         }

//-------------------------------Cookie退出(加一個退出按鈕)-------------------------------

//退出  

 代碼如下 複製代碼
HttpCookie hcUserName1 = new HttpCookie("username");  
hcUserName1.Expires = System.DateTime.Now.AddDays(-7);  
hcUserName1.Value = username;  
HttpCookie hcPassword1 = new HttpCookie("password");  
hcPassword1.Expires = System.DateTime.Now.AddDays(-7);  
hcPassword1.Value = password;  
Response.Cookies.Add(hcUserName1);  
Response.Cookies.Add(hcPassword1); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.