I have a cookie that I add to the response, but if a cookie with the same key already exists I want to remove it otherwise I end up with 2 cookies of the same key.

I thought by simply expiring the cookie it would remove it from the browser?

HttpCookie cookie = new HttpCookie("UserCookie");
cookie.Value = encTicket;

if (HttpContext.Current.Request.Cookies["UserCookie"] != null)
    ClearCookie("UserCookie");

HttpContext.Current.Response.Cookies.Add(cookie);


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

    HttpCookie cookie = new HttpCookie(key)
    {
        Expires = DateTime.Now.AddMonths(-1),
        Value = null
    };

    _response.Cookies.Add(cookie);
}

Any help much appreciated.

有帮助吗?

解决方案 3

For now I'm just selecting the last cookie value in the collection, although I realise this is a massive hack. Any better suggestions very welcome.

string value = "";
for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
{
    if (HttpContext.Current.Request.Cookies[i].Name == "UserCookie")
    value = HttpContext.Current.Request.Cookies[i].Value;
}

其他提示

"You cannot directly delete a cookie on a user's computer. However, you can direct the user's browser to delete the cookie by setting the cookie's expiration date to a past date. The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it."

Please read the following article for more detail.

http://msdn.microsoft.com/en-us/library/ms178195(v=vs.85).aspx

Here is how I'm writing my cookie.

protected string CookieSession(Enums.CookieSessionTypes sessionTypes, string cookieValue = "")
    {
        string sessionId = string.Empty;

        var cookie = new HttpCookie(CookieName);

        switch (sessionTypes)
        {
            case Enums.CookieSessionTypes.Add:

                cookie.Values[SessionIdConst] = cookieValue;
                cookie.Expires = DateTime.Now.AddDays(1);
                Response.Cookies.Add(cookie);
                sessionId = cookieValue;

                break;
            case Enums.CookieSessionTypes.Delete:
                cookie.Values[SessionIdConst] = cookieValue;
                cookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(cookie);

                break;
        }


        return sessionId;
    }

Give it a try, should work

My cookie was not expiring properly because it had been set with a different path than the actual one, and unlike the domain name portion of a URL, cookie paths are case-sensitive. The only way to fix this is to set up a mechanism in your web server or code to redirect to a case-sensitive canonical URL from any other URL casing. Then your cookies will start working again.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top