码迷,mamicode.com
首页 > 其他好文 > 详细

Cookie存储数据

时间:2014-09-02 00:08:43      阅读:284      评论:0      收藏:0      [点我收藏+]

标签: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存储数据

标签:http   ar   数据   art   代码   sp   amp   on   时间   

原文地址:http://www.cnblogs.com/ss977/p/3950474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!