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);