Cookie儲存資料

來源:互聯網
上載者:User

標籤: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儲存資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.