2010-08-12 33 views
1

我試圖保持一些數據Cookie,但回發後,如果我檢查在頁面加載的值總是空的cookie的值爲什麼餅乾總是回發後空

這是我如何設置和獲取餅乾

private static string GetCookie(string name) 
{ 
    return HttpContext.Current.Response != null ? HttpContext.Current.Response.Cookies[name].Value : string.Empty; 
} 

private static void SetCookie(string name, string value) 
{ 
    HttpContext.Current.Response.Cookies[name].Value = value; 
    HttpContext.Current.Response.Cookies[name].Expires = DateTime.Now.AddDays(ExpireTimeInDays); 
} 
+0

從你在哪裏調用這些方法?從ASPX頁面中的特定事件?你可以在你的頁面或處理程序中顯示代碼來調用這些代碼嗎? – Eilon 2010-08-12 18:14:59

+0

我認爲你需要從請求中獲取cookie。 – dotjoe 2010-08-12 18:16:48

回答

11

的getCookie()需要使用Request.Cookie不會是Response.Cookie

3

HttpResponse.Cookies

ASP.NET包含兩個固有cookie 集合。訪問 通過Cookie集合 HttpRequest包含由客戶端發送到Cookie頭中的 服務器的Cookie 。通過 集合訪問的 集合HttpResponse 包含在 服務器上創建並在Set-Cookie標頭中發送到客戶端 的新Cookie。

後您使用 的HttpResponse .. ::。Cookies集合添加一個cookie, 的cookie是在 立即可用的HttpRequest .. ::。餅乾 收集,即使響應已 尚未發送給客戶。

因此改變你獲得使用該請求