我使用下面的代碼來設置我的asp.net mvc的一個cookie(C#)應用:的Cookie不會被刪除
public static void SetValue(string key, string value, DateTime expires)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
HttpCookie cookie = new HttpCookie(key, value) { Expires = expires };
_response.Cookies.Set(cookie);
}
我需要當用戶點擊註銷刪除的cookie。設置的Cookie不能通過清除/刪除來刪除/刪除。代碼如下:
public static void Clear()
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
_request.Cookies.Clear();
_response.Cookies.Clear();
}
public static void Remove(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
if (_request.Cookies[key] != null)
{
_request.Cookies.Remove(key);
}
if (_response.Cookies[key] != null)
{
_response.Cookies.Remove(key);
}
}
我已經嘗試了上述兩個函數,但仍然cookie存在,當我嘗試檢查存在。
public static bool Exists(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
return _request.Cookies[key] != null;
}
這裏有什麼問題?或者我需要做什麼來刪除/刪除cookie?
這還不夠。看看下面我的回覆中的代碼。 – 2011-03-23 20:38:19
@Ed - 你的代碼和我的代碼完全一樣,除了它有一些不必要的行,比如檢查一個新實例化的對象是否存在(它的確如此)。你覺得這個不見了? – 2011-03-23 22:15:20
是的,空檢查是不必要的。但我發現我需要給兩個: 「從服務器刪除(對客戶端沒有影響) .Response.Cookies.Remove(鍵) 」到期,客戶端 .Response.Cookies.Add(餅乾) 否則該cookie從未真正被刪除。從我看到的微軟代碼和其他樣本來看,做這兩個似乎是保證cookie確實被刪除的方法。 – 2011-03-24 13:45:24