收录日期:2021/02/27 20:43:22 时间:2009-03-14 05:04:42 标签:c#,asp.net,cookies

I'm calling the following code:

protected void SetCookieValue(
    string sCookieName, object oValue, DateTime dtExpires)
{
    Response.Cookies[sCookieName].Value = Utility.ToStringValue(oValue);
    Response.Cookies[sCookieName].Expires = dtExpires;
    Response.Cookies.Add(Response.Cookies[sCookieName]);
}

With a date set to 30 days prior:

SetCookieValue(sCookieName, null, DateTime.Now.AddDays(-30.0));

In order to force the cookie to be expired. It's working on my dev box (Windows 7, IIS7), but failing now on IIS6. I didn't change this code and it seemed to be working for over a year now, but on the production site, I cannot clear this cookie.

Browser in IE8 in compat mode (for hitting dev and production.

Any ideas?


Thanks for the nudge in the right direction. Here's what I ended up with:

protected void SetCookieValue(
        string cookieName, object value, DateTime expireDate)
{
    HttpCookie cookie = new HttpCookie(cookieName);
    cookie.Value = Utility.ToStringValue(value);
    cookie.Expires = expireDate;

    if (Request.Cookies[cookieName] != null)
    {
        Response.SetCookie(cookie);
    }
    else
    {
        Response.Cookies.Add(cookie);
    }
}

So when I kill a cookie, I call this method with the name, a null value and a DateTime.MinValue expiration date. if the cookie exists, it gets updated and if not, it gets added with the expiration.

I wanted to use the same function to create or kill a cookie, hence keeping it out of its own DeleteCookie method. I also renamed the cookies completely to insure I was starting fresh. I may get a little user pushback on that, but whoops! :)

Thanks! Answer is marked as the one who set me in the right direction.

You should retrieve the cookie from Request.Cookies, and then add the expired cookie to Response.Cookies:

public void DeleteCookie(string cookieName)
{
    if (Request.Cookies[cookieName] != null)
    {
        HttpCookie myCookie = new HttpCookie(cookieName);
        myCookie.Expires = DateTime.Now.AddDays(-1d);
        Response.Cookies.Add(myCookie);
    }
}

I'm no asp.net expert, but without playing around with your code at all, the only thing that looks weird to me is that you're calling:

Response.Cookies.Add(Response.Cookies[sCookieName]);

after already calling

Response.Cookies[sCookieName].Value = Utility.ToStringValue(oValue);
Response.Cookies[sCookieName].Expires = dtExpires;

This seems redundant to me and may be causing some odd behavior. And, from my limited experience, those first two lines are all you really need.

The other option is that seeing as though IE8 is still in pre-release, it may be having some issues with cookie handling. Try with another browser and see if you still get the same results.