Friday, January 09, 2009

Cookies in Asp.net - An Important Tip

Hi folks,

In this post i want to show how to create a cookie in asp.net page which contains a counter ,This counter will be increased every time you visit the page.

The tip which i want to highlight here-(I got this question from one of my firends),That when you try to update the cookie value in asp.net you have to update the expiry date of the httpcookie object,otherwise the asp.net will store the default value which is : 1/1/0001,which let your code to create a cookie every time instead of update the counter value in the cookie file.

The code to do this on page_load event in C# :


if (Request.Cookies["counter"] != null)
{
HttpCookie coo=Request.Cookies["counter"];
int x = int.Parse(coo.Value);
x += 1;
coo.Value = x.ToString();
coo.Expires = DateTime.Now.AddDays(7);// if you omit this line,the cookie will be created each time.

Response.Cookies.Add(coo);
Response.Write(coo.Value);
}
else
{
HttpCookie coo = new HttpCookie("counter", "0");
coo.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(coo);
Response.Write(coo.Value);
}



The code for this post is uploaded here:
http://cid-4bc94054914a6469.skydrive.live.com/self.aspx/Blog%20Code/CookiePageTest.aspx.cs


Hope this helps.

Regards,
Mostafa arafa
Post a Comment