2011-10-27 68 views
4

您能告訴我我在這裏做錯了什麼。 爲什麼當我重新加載網頁的Cookie數據不存儲:asp.net 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中,然後我重新加載頁面(刷新)並且值爲空。

有什麼想法?

+0

檢查服務器日期/時間。此外,'Page_Load'將始終在'CheckBoxRememberMe_Click'之前執行,因此我只會在第二次加載頁面後期待cookie(點擊複選框後)。 – Oded

+0

正如我所提到的,我在刷新頁面時檢查Page_Load。所以我確定在讀取該值之前調用該值的設置(在頁面的第二次加載時)。 – Ranch

回答

8

在檢查您想要發出請求的cookie而不是將cookie添加到響應時。

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

就是這樣!我應該使用Request.Cookies – Ranch