標籤:http ar 資料 art 代碼 sp amp on 時間
首先在載入事件裡驗證Cookie裡面是否有資料:
//若cookie不為空白,則將資料填充到text中
if (Request.Cookies["username"] != null) {
this.txtUserName.Text = Request.Cookies["username"].Value;
this.txtPwd.Text = Request.Cookies["pwd"].Value;
}
在登入事件裡寫入代碼:10分鐘後到期
String name = this.txtUserName.Text;
String userPwd = this.txtPwd.Text;
if (name == "admin" && userPwd == "123")
{
HttpCookie cookie1 = new HttpCookie("username", name);
//設定到期時間
cookie1.Expires = DateTime.Now.AddMinutes(10);
//儲存到cookie中
Response.Cookies.Add(cookie1);
HttpCookie cookie2 = new HttpCookie("pwd", userPwd);
cookie2.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Add(cookie2);
ClientScript.RegisterStartupScript(this.GetType(), "", "alert(‘登入成功,資料已經存於Cookie‘)", true);
在刪除事件裡寫入代碼:
//刪除儲存在用戶端Cookie的原理:
//1、先建立與用戶端儲存Cookie的名字相同的Cookie(目的:為了覆蓋用戶端對應名字的Cookie)
//2、將Cookie的到期時間設定為目前時間(目的:將用戶端對應名字的Cookie覆蓋後,自己馬上到期)
//3、將Cookie通過Response儲存到用戶端
//自殺式刪除
HttpCookie cookie1 = new HttpCookie("username",null);//用null覆蓋原本文字框中的資料
//設定有效時間為目前時間
cookie1.Expires = DateTime.Now;
Response.Cookies.Add(cookie1);
HttpCookie cookie2 = new HttpCookie("pwd", null);
//設定有效時間為目前時間
cookie1.Expires = DateTime.Now;
Response.Cookies.Add(cookie2);
ClientScript.RegisterStartupScript(this.GetType(),"","alert(‘刪除成功‘)",true);
Cookie儲存資料