Cookie未被删除

Pra*_*sad 34 cookies asp.net-mvc

我使用以下代码在我的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);
}
Run Code Online (Sandbox Code Playgroud)

我需要在用户单击注销时删除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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了上述两种功能,但是当我尝试检查存在时,cookie仍然存在.

public static bool Exists(string key)
{
    var httpContext = new HttpContextWrapper(HttpContext.Current);
    _request = httpContext.Request;
    _response = httpContext.Response;
    return _request.Cookies[key] != null;
}
Run Code Online (Sandbox Code Playgroud)

这可能有什么问题?或者我要删除/删除cookie需要做什么?

Gre*_*ech 55

清除响应的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);
}
Run Code Online (Sandbox Code Playgroud)


Rip*_*ppo 6

只是为了添加其他内容,我还将值传递回 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

Request和Response对象中的Cookies集合不是浏览器中Cookie的代理,它们是浏览器向您发送和向您发送回的Cookie的集合。如果您从请求中删除cookie,则完全是服务器端的,如果响应中没有cookie,那么您就不会将任何东西发送回客户端,这不会更改浏览器中的cookie集。所有。

要删除Cookie,请确保它响应Cookie集合中,但在过去的到期时间。


bik*_*868 5

在尝试了一段时间并尝试了这里所有其他答案之后,我发现这里没有一个答案是完全正确的。

正确的部分是您必须发送过期的 cookie 才能实现删除。其他人没有注意到的部分(但在 Ed DeGagne 发布的 Microsoft 代码中得到了演示)是用于删除的 cookie 选项必须与最初用于设置 cookie 的 cookie 选项完全匹配。

例如,如果您最初使用 HttpOnly 选项创建 cookie,则在删除 cookie 时还必须设置此选项。我预计确切的行为会因浏览器的不同而变化,并且可能会随着时间的推移而变化,因此长期有效的唯一安全的选择是确保删除响应中的所有 cookie 选项与最初用于创建 cookie 的 cookie 选项完全匹配。