Friday, July 9, 2010

Changing cookie expiration time

Changing cookie expiration time is not straight forward. It is not as easy as setting the http cookie's property Expires to required value as shown below.

HttpContxt.Response.Cookies["UserID"].Expires = DateTime.Now.AddMinutes(20);

I was using the above line of code in one of my projects as I wanted to make sure the cookie's expiration time gets updated for every user action. I added that line of code in the method where I check for authentication in each page request. But I was wondering with it's strange behavior as it is crashing the web page to load. I did spend some time on fixing it but got no luck.

After a while I got the solution which is explained in an MSDN article http://msdn.microsoft.com/en-us/library/ms178194.aspx. As explained the article, we must recreate the cookie with value and expiration time as we normally do when adding a cookie. So changing cookie is not at all different from creating a cookie in the browser. Finally I changed my code to recreate the cookie where updating cookie expiration time is needed. And it is perfectly working fine.

The correct code it worked was:

HttpContxt.Response.Cookies["UserID"].Value= UserID;
HttpContxt.Response.Cookies["UserID"].Expires = DateTime.Now.AddMinutes(20);

kick it on DotNetKicks.com