2009-11-20 152 views
27

我使用下面的代碼來設置我的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?

回答

49

清除響應的cookie不會指示瀏覽器清除cookie,它只是不會將cookie發送回瀏覽器。要指示瀏覽器清除Cookie,您需要告訴它Cookie已過期,例如

public static void Clear(string key) 
{ 
    var httpContext = new HttpContextWrapper(HttpContext.Current); 
    _response = httpContext.Response; 

    HttpCookie cookie = new HttpCookie(key) 
     { 
      Expires = DateTime.Now.AddDays(-1) // or any other time in the past 
     }; 
    _response.Cookies.Set(cookie); 
} 
+0

這還不夠。看看下面我的回覆中的代碼。 – 2011-03-23 20:38:19

+1

@Ed - 你的代碼和我的代碼完全一樣,除了它有一些不必要的行,比如檢查一個新實例化的對象是否存在(它的確如此)。你覺得這個不見了? – 2011-03-23 22:15:20

+0

是的,空檢查是不必要的。但我發現我需要給兩個: 「從服務器刪除(對客戶端沒有影響) .Response.Cookies.Remove(鍵) 」到期,客戶端 .Response.Cookies.Add(餅乾) 否則該cookie從未真正被刪除。從我看到的微軟代碼和其他樣本來看,做這兩個似乎是保證cookie確實被刪除的方法。 – 2011-03-24 13:45:24

4

Cookies集合在Request和Response對象不適合在瀏覽器中的cookies代理,他們是一組什麼樣的cookie瀏覽器發送你,你送回去。如果你從請求中刪除一個cookie,它完全是服務器端,如果你在響應中沒有cookie,你只是不會將任何東西發送回客戶端,這不會改變瀏覽器中的cookie集所有。

要刪除一個cookie,請確保它在響應cookie集合中的,但過去有一個到期時間。

4

只是爲了添加別的東西,我也將值返回爲空,例如,

public static void RemoveCookie(string cookieName) 
    { 
     if (HttpContext.Current.Response.Cookies[cookieName] != null) 
     { 
      HttpContext.Current.Response.Cookies[cookieName].Value = null; 
      HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.Now.AddMonths(-1); 
     } 
    } 
+1

謝謝,這真的是所有需要的 – spojam 2014-11-21 03:49:34

3

來實現這一點的最好辦法是使用像反射器的工具,看看System.Web.Security.FormsAuthentication.SignOut方法如何實現移除身份驗證cookie。

在Reflector中,打開System.Web並導航到FormsAuthentication對象並找到SignOut方法。右鍵單擊它並選擇「反彙編」(從菜單中選擇您的語言)。

VB.NET

Public Shared Sub SignOut() 

    FormsAuthentication.Initialize 

    Dim current As HttpContext = HttpContext.Current 
    Dim flag As Boolean = current.CookielessHelper.DoesCookieValueExistInOriginal("F"c) 
    current.CookielessHelper.SetCookieValue("F"c, Nothing) 

    If (Not CookielessHelperClass.UseCookieless(current, False, FormsAuthentication.CookieMode) OrElse current.Request.Browser.Cookies) Then 
     Dim str As String = String.Empty 

     If (current.Request.Browser.Item("supportsEmptyStringInCookieValue") = "false") Then 
      str = "NoCookie" 
     End If 

     Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, str) 

     cookie.HttpOnly = True 
     cookie.Path = FormsAuthentication._FormsCookiePath 
     cookie.Expires = New DateTime(&H7CF, 10, 12) 
     cookie.Secure = FormsAuthentication._RequireSSL 

     If (Not FormsAuthentication._CookieDomain Is Nothing) Then 
      cookie.Domain = FormsAuthentication._CookieDomain 
     End If 

     current.Response.Cookies.RemoveCookie(FormsAuthentication.FormsCookieName) 
     current.Response.Cookies.Add(cookie) 
    End If 

    If flag Then 
     current.Response.Redirect(FormsAuthentication.GetLoginPage(Nothing), False) 
    End If 

End Sub 

利用上述作爲一個例子,我能夠在共享組件創建名爲RemoveCookie()的常用方法,代碼如下:

VB .NET

''' <summary> 
''' Method to remove a cookie 
''' </summary> 
''' <param name="key">Key</param> 
''' <remarks></remarks> 
Public Shared Sub RemoveCookie(ByVal key As String) 

    ' Encode key for retrieval and remove cookie 
    With HttpContext.Current 
     Dim cookie As New HttpCookie(.Server.UrlEncode(key)) 

     If Not IsNothing(cookie) Then 
      With cookie 
       .HttpOnly = True 
       .Expires = New DateTime(&H7CF, 10, 12) 
      End With 

      ' Remove from server (has no effect on client) 
      .Response.Cookies.Remove(.Server.UrlEncode(key)) 
      ' Add expired cookie to client, effectively removing it 
      .Response.Cookies.Add(cookie) 
     End If 

    End With 

End Sub 

已經使用FireBug和Cookie加載項進行了測試FireBug(在FireFox中),我可以證明cookie立即被刪除。

有任何問題,隨時給我發消息。

+0

順便說一句,如果你不是UrlEncoding你的密鑰和值(你應該是),那麼只需刪除.Server.UrlEncode(key),然後用鍵替換。 – 2011-03-23 20:37:06

+0

很多代碼並沒有太多解釋。可以更好地回答這個問題。 – 2013-07-18 10:20:27

+1

這其實很明顯...... – 2013-07-19 12:43:00