Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

asp.net mvc - Cookie is not deleted

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?

question from:https://stackoverflow.com/questions/1771165/cookie-is-not-deleted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...