首页 > 代码库 > cookie在vs重新run的时候丢失

cookie在vs重新run的时候丢失

今天写个关于http cookie的demo,发现只要vs重新运行后cookie的值就会丢失,代码如下
protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie _userInfoCookies = Request.Cookies["UserName"];
            string city;
            if (_userInfoCookies != null)
            {
                city = _userInfoCookies["City"];
                Session["location"] = city;
                Response.Redirect("Berava.aspx");
            }
        }
        protected void Moveto_Click(object sender, EventArgs e)
        {
            Session["location"] = worlddrdolist.SelectedItem.Value;
            if (CheckBox1.Checked)
            {
                HttpCookie _userInfoCookies = new HttpCookie("UserName");
                _userInfoCookies["City"] = worlddrdolist.SelectedValue.ToString();

                Response.Cookies.Add(_userInfoCookies);
            }
            Response.Redirect("Berava.aspx");
        }
最后才发现是因为没有设置cookie的过期时间导致(Expire),默认cookie只是在当前会话有效,所以vs重新运行的时候就是一个新的会话,这时cookie就已经失效了,只要将cookie设置一个过期时间就ok了,像下面这样(有效时间为一天):
_userInfoCookies.Expires = DateTime.Now.AddDays(1);