首页 > 代码库 > Cookie存储数据

Cookie存储数据

 首先在加载事件里验证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存储数据