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

2 comments:

Anonymous said...

Cool post you got here. I'd like to read something more about this topic. Thank you for giving this data.

Anonymous said...

Good fill someone in on and this post helped me alot in my college assignement. Say thank you you seeking your information.