Cookie is not deleted

Viewed 29853

I am using the following code to set a cookie in my asp.net mvc(C#) application:

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:

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.

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?

6 Answers

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.

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.

Response.Cookies["key"].Expires= DateTime.Now;

Related