asp.net-mvc Cookie 未删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1771165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cookie is not deleted
提问by Prasad
I am using the following code to set a cookie in my asp.net mvc(C#) application:
我正在使用以下代码在我的 asp.net mvc(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);
}
I need to delete the cookies when the user clicks logout. The set cookie is not removing/deleting with Clear/Remove. The code is as below:
当用户单击注销时,我需要删除 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);
}
}
I have tried both the above functions, but still the cookie exists when i try to check exist.
我已经尝试了上述两个功能,但是当我尝试检查存在时cookie仍然存在。
public static bool Exists(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
return _request.Cookies[key] != null;
}
What may be problem here? or whats the thing i need to do to remove/delete the cookie?
这里可能有什么问题?或者我需要做什么来移除/删除 cookie?
回答by Greg Beech
Clearing the cookies of the response doesn't instruct the browser to clear the cookie, it merely does not send the cookie back to the browser. To instruct the browser to clear the cookie you need to tell it the cookie has expired, e.g.
清除响应的 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);
}
回答by Skirwan
The Cookies collection in the Request and Response objects aren't proxies for the cookies in the browser, they're a set of what cookies the browser sends you and you send back. If you remove a cookie from the request it's entirely server side, and if you have no cookies in the response you're just not going to send any thing back to the client, which won't change the set of cookies in the browser at all.
Request 和 Response 对象中的 Cookies 集合不是浏览器中 cookie 的代理,它们是浏览器向您发送和您发送回的 cookie 的集合。如果您从请求中删除 cookie,则它完全是服务器端,如果响应中没有 cookie,您就不会将任何内容发送回客户端,这不会更改浏览器中的 cookie 集全部。
To delete a cookie, make sure that it isin the response cookie collection, but has an expiration time in the past.
要删除Cookie,请确保它是响应Cookie集合中,但在过去的到期时间。
回答by Rippo
Just to add something else I also pass the value back as null e.g.
只是为了添加其他东西,我也将值作为 null 传回,例如
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);
}
}
回答by Ed DeGagne
The best way to implement this is to use a tool like Reflector and see how the System.Web.Security.FormsAuthentication.SignOut method implements removing the authentication cookie.
实现这一点的最佳方法是使用 Reflector 之类的工具,并查看 System.Web.Security.FormsAuthentication.SignOut 方法如何实现删除身份验证 cookie。
In Reflector, open up System.Web and navigate to the FormsAuthentication object and find the SignOut method. Right click on it and select "Disassemble" (Choose your language from the menu).
在 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
With the above as an example, I was able to create a common method called RemoveCookie() in a shared assembly, code is below:
以上面为例,我能够在共享程序集中创建一个名为 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
Having tested this using FireBug and the Cookie add-in for FireBug (in FireFox), I can attest that the cookie immediately gets removed.
使用 FireBug 和 FireBug 的 Cookie 插件(在 FireFox 中)对此进行了测试后,我可以证明 cookie 会立即被删除。
Any questions, feel free to message me.
有任何问题,请随时给我留言。
回答by bikeman868
After playing around with this for some time and trying all of the other answers here I discovered that none of the answers here are totally correct.
在玩了一段时间并在这里尝试了所有其他答案之后,我发现这里没有一个答案是完全正确的。
The part that is correct is that you have to send an expired cookie to effect the deletion. The part that nobody else picked up on (but is demonstrated in the Microsoft code posted by Ed DeGagne) is that the cookie options for the deletion must match exactly the cookie options that were used to set the cookie in the first place.
正确的部分是您必须发送过期的 cookie 才能实现删除。其他人没有注意到的部分(但在 Ed DeGagne 发布的 Microsoft 代码中进行了演示)是用于删除的 cookie 选项必须与最初用于设置 cookie 的 cookie 选项完全匹配。
For example if you originally created the cookie with the HttpOnly option then you must also set this option when deleting the cookie. I expect the exact behavior will vary across browsers and probably over time, so the only safe option that will work long-term is to make sure that all of the cookie options in the deletion response match exactly the cookie options used to create the cookie originally.
例如,如果您最初使用 HttpOnly 选项创建 cookie,则在删除 cookie 时还必须设置此选项。我预计确切的行为会因浏览器而异,并且可能会随着时间的推移而有所不同,因此唯一能长期有效的安全选项是确保删除响应中的所有 cookie 选项与最初用于创建 cookie 的 cookie 选项完全匹配.

