Working with Cookies in ASP.NET

ASP.NET has 3 classes which allow you to work with Cookies.

HttpCookie: provides a way to create and manipulate individual HTTP cookies.
HttpResponse: The Cookies property allows to create and save cookies on client machines.
HttpRequest: The Cookies property allows access to cookies from the client maintains.

How to create a Cookie ?

It is really easy to create a cookie in ASP.NET. You can use the Response object in ASP.NET to create cookies as key-value pairs.

Response.Cookies("UserName").Value = "Mr. John"
Response.Cookies("UserName").Expires = DateTime.Now.AddDays(1)

In the above sample code, the first line will save a cookie with the name "UserName" and value "Mr. John" to the client computer.

The second line says that this cookie is valid for 1 more day from current time.

As shown above, you can store any key-value pairs to client computer as cookies.

How to retrieve values from Cookies ?

You can use the Request object to retrieve values from the cookies which are already stored.

Dim name As String = Me.context.Request.Cookies("UserName").Value

If there is no cookie with the name "UserName", the above code sample will return an empty string.

The HttpCookie class

HttpCookie is another usefull class in ASP.NET which allows you to work with Cookies. Here is a code snippet which shows how to use this class:

Dim myCookie As New HttpCookie("UserName")
myCookie.Value = "Mr. John"
myCookie.Expires = DateTime.Now.AddDays(1)
myCookie.Domain = ""

How cookies are stored and retrieved ?

You saw the sample code which uses Request and Response objects to store and retrieves values in Cookies. Do you know how they really work?

When you execute the line

 Response.Cookies("UserName").Value = "Mr. John",

 it runs on the server. It has no connection with the client computer. Then how is it saving on the client computer?

When your browser request a URL from the web server, what it gets back is a 'big packet'. This packet has lot of information which includes the meta data, cookies, content of the page to be displayed to you etc. So, the cookies is part of the response the browser gets back from the web server. Browser knows what to do with each piece of data in the response. It saves the cookies to your local computer, and displays the page content in your browser.