Sunday, January 24, 2010

Writing and Reading Cookies in ASP.Net


In previous blog we learned about basics of cookies. Now let’s see how we can play with these cookies. We can write, use and retrieve these cookies. For working with cookies we need following 3 classes:-

1) HttpCookie: - It is used to create HTTP cookies.
2) HttpResponse: - This is a property which is used to create and save cookies on client machine.
3) HttpRequest: - This property is used to retrieve values of cookies.

Let’s see how to write and retrieve cookies: -

1) Write cookies: -
For writing cookies to visitor’s computer we need Response.Cookies command.
For example: -
If we want to write userId in cookie then we need to write in following way: -
Response.Cookies (“userId”).Value = 1
By above sentence we can save cookie with userId 1 to computer.
If we want to put expiry date then we need to write in following way: -
Response.Cookies (“userId”).Expires = DateTime.Now.AddDays (8)
By above sentence we can put expiry date after 8 days from now. So that after 8 days that particular cookie will be discarded i.e. its validity will get over in 8 days.

We can also write above code in following manner: -

Dim cookie As New HttpCookie (“userId”)
cookie.Value = 1
cookie.Expires = DateTime.Now.AddDays (8)
cookie. Domain = “abc.com”
Response.Cookies. Add (cookie)
From above code also we can save cookie.

2) Retrieve cookies: -
For retrieving cookies to visitor’s computer we need Request. Cookies command.
For example: -
Dim uId as Integer
uId = Request. Cookies (“userId”). Value

Now you must be thinking how exactly this cookie thing works. The process starts from web server. When you request for any page, web server sends few things like cookies, content etc. to browser. Then things like cookies get saved on your computer and the page gets displayed to you. So you can say cookies are a response from web server. So we use ‘Response’ for adding cookies. Similarly we use ‘Request’ for retrieving cookies as browser is requesting for cookies to web server.

No comments:

Post a Comment