cookie的使用,获取与注销

登录页面 

if (Login(this.txtName.Text.Trim().ToString(),this.txtPass.Text.Trim().ToString()))
            {
                HttpCookie cookie = new HttpCookie("user");
                cookie.Values.Add("username",this.txtName.Text);
                cookie.Values.Add("userpass",this.txtPass.Text);
               
                if (this.ckLogin.Checked)
                {
                    DateTime dat = DateTime.Now;//定义时间对象
                    TimeSpan ts = new TimeSpan(30, 0, 0, 0);//cookie有效作用时间,具体查msdn

                    cookie.Expires = dat.Add(ts);//添加作用时间


                    //cookie.Expires.AddDays(30);
                   
                }
                Response.AppendCookie(cookie);
                Thread.Sleep(2000);
                Response.Redirect("index.aspx");
            }
            else
            {
                this.lblError.Text = "用户名或密码有误,请重新输入!";
            }

 

首页,index.aspx,里面有一个注销按钮

 

首先获取,在页面加载的时候

 protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["user"];
        if (cookie == null)
        {
            Response.Redirect("~/Admin_Manager/Login.aspx");
        }
        else
        {
            string name = cookie.Values["username"];
            this.lblName.Text = name;
        }
    }

当点击注销的时候

 

 protected void lkZhuXiao_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["user"];
        //首先获取用户名(也可获取其他,例如密码什么的)
        string username=cookie.Values["username"];
        //移除用户名
        cookie.Values.Remove(username);
        //设置过期时间
        cookie.Expires = DateTime.Now.AddDays(-1);
        //重新添加cookie,现在的cookie就是注销了当前用户
        Response.Cookies.Add(cookie);
        //Request.Cookies["user"].Expires.AddDays(-1);
        Response.Redirect("~/Admin_Manager/zhuxiao.aspx");
      
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值