ASP.NET Cookie Update Value Without Updating Expiration?

11,582

The ASP.NET HttpCookie class can not initialize the Expires property upon reading in a cookie from an HTTP request (since the HTTP specification doesn't require the client to even send the Expiration value to the server in the first place). And if you don't set the Expires property before you set the cookie back in the HTTP Response, than it turns it into a session cookie instead of a persistent one.

If you really must keep the expiration, than you could set the initial expiration date as part of the cookie value, then when you read the cookie in, parse out the value and set the new expiration to match.

An example that doesn't include any other data so the cookie isn't really helpful -- you would have to serialize it somehow with the actual data you want to store:

HttpCookie cookie = HttpContext.Current.Request.Cookies[constantCookie];
DateTime expires = DateTime.Now.AddYears(1);

if (cookie == null) {
    cookie = new HttpCookie(constantCookie);
} else {
    // cookie.Value would have to be deserialized if it had real data
    expires = DateTime.Parse(cookie.Value);  
}

cookie.Expires = expires;
// save the original expiration back to the cookie value; if you want to store
// more than just that piece of data, you would have to serialize this with the
// actual data to store
cookie.Value = expires.ToString();

HttpContext.Current.Response.Cookies.Set(cookie);
Share:
11,582
aherrick
Author by

aherrick

http://twitter.com/andrew_herrick http://andrewherrick.com Run, code, slick.

Updated on June 25, 2022

Comments

  • aherrick
    aherrick almost 2 years

    Is it possible to update an ASP.NET cookies value without also having to update the expiration time? I have found that if I try and update a Cookie without also updating the expiration, that cookie no longer exists. I have the following code which I am try to modify. What's the point of having an expiration, if every time the cookie value is updated, so is the expiration?

            HttpCookie cookie = HttpContext.Current.Request.Cookies[constantCookie];
    
            if (cookie == null)
                cookie = new HttpCookie(constantCookie);
    
            cookie.Expires = DateTime.Now.AddYears(1);
            cookie.Value = openClose;
            HttpContext.Current.Response.Cookies.Set(cookie);