Saturday, January 8, 2011

ASP.NET Cookies Expires property is not initialized

It appears that you cannot read is the cookie's expiration date and time - HttpCookie.Expires property. It turns out that when the browser sends cookie information to the server, the browser does not include the expiration information. You can read the Expires property, but it always returns a date-time value of zero.

Browser is responsible for managing cookies; the Expires property is an example of this. The primary purpose of the Expires property is to help the browser perform housekeeping on its store of cookies. From the server's perspective, the cookie either exists or it does not; the expiration is not a useful piece of information on the server side. Therefore, the browser does not provide this information when it sends the cookie. If you are concerned about the expiration date of a cookie, you must reset it.

At times you might want to modify a cookie, perhaps to change its value or to extend its expiration. (Remember that you cannot read a cookie's expiration date because the browser does not pass the expiration information to the server.)

You do not really directly change a cookie, of course. Although you can get a cookie from the Request.Cookies collection and manipulate it, the cookie itself still lives someplace on the user's hard disk. So modifying a cookie really consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.

The following example shows how you might change the value of a cookie that stores a count of the user's visits to the site:

Dim counter As Integer
If Request.Cookies("counter") Is Nothing Then
counter = 0
counter = CInt(Request.Cookies("counter").Value)
End If
counter += 1
Response.Cookies("counter").Value = counter.ToString
Response.Cookies("counter").Expires = DateTime.Now.AddDays(1)


No comments: