【问题标题】:asp.net cookie not savedasp.net cookie 未保存
【发布时间】:2014-11-22 22:27:29
【问题描述】:

你能告诉我我在这里做错了什么吗? 为什么我重新加载页面时没有存储Cookie数据:

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      // it is always null !!!!               
      if (Response.Cookies["user_id"].Value != null) 
      {
          //code never gets here
      }
   }
}

这是存储 cookie 的代码(单击复选框后):

protected void CheckBoxRememberMe_Click(object sender, EventArgs e)
{
    Response.Cookies["user_id"].Value = tbUserID.Text;
    Response.Cookies["user_id"].Expires = DateTime.Now.AddDays(15);
}

所以:我点击复选框,tbUserID文本框的值存储在HttpCookie中,然后我重新加载页面(刷新)并且值为null。

有什么想法吗?

【问题讨论】:

  • 检查服务器日期/时间。此外,Page_Load 将始终在CheckBoxRememberMe_Click 之前执行,所以我只希望在第二次加载页面后(在单击复选框之后)有一个 cookie。
  • 正如我所提到的,我在刷新页面时检查 Page_Load。所以我确定在读取值之前调用了值的设置(在页面的第二次加载时)。

标签: c# asp.net cookies


【解决方案1】:

在检查 cookie 时,您要发出请求,而不是将 cookie 添加到响应中。

   if (Request.Cookies["user_id"].Value != null) 
   {
       //code should get here
   }

【讨论】:

  • 就是这样!我应该使用 Request.Cookies
猜你喜欢
  • 2011-05-16
  • 2019-01-19
  • 2010-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
相关资源
最近更新 更多