Cookies in asp.net applications

In this post we are going to see a step by step example on how to read,write,delete cookies in asp.net websites.

Cookies are small pieces of text that you can associate with a website which are transfered down to the user's computer when the user visits the website.

You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 express editions work fine).

I will use VS 2010 Ultimate edition and VB.net as the .Net language of choice.

Before we begin it is very important to note some of the limitations of cookies. They store relatively small amount of information about 4kbytes.

Browsers limit the number of cookies associated with a website ( 20 cookies for a certain website ). There is also a limit on how many cookies a browser can handle regarding all websites and that is about 300.

All the data in cookies is stored as text so bear that in mind that you should not store sensitive information in a cookie. You should use the information in the cookie to identify a user, a user's last visit e.t.c

1) Create an Asp.net web site and name it as you want.

2) Let's add a cookie in the cookies collection. In the Page_Load event handling routine of the default.aspx page type

Response.Cookies("LastVisit").Value = DateTime.Now.ToString()
Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(10)

3)  We add a new cookie now that it will be stored in the user's computer and we set it to expire after 10 days.So if someone visits our website today and then it visits it after 12 days, the browser will delete the cookie

from the users hard disk.Comment out the two line of code in the Page_Load event handling routine.We can use an alternative way to create a cookie and write information on it.

Dim mycookie As HttpCookie = New HttpCookie("LastVisit")
mycookie.Value = DateTime.Now.ToString()
mycookie.Expires = DateTime.Now.AddDays(10)
Response.Cookies.Add(mycookie)

4)  You can store multiple values in the same cookie with the help of subkeys. Comment out the 4 lines of code above. Type the following lines of code in the Page_Load routine

Response.Cookies("mydata")("LastVisit") = DateTime.Now.ToString()
Response.Cookies("mydata")("username") = "fofo"
Response.Cookies("mydata").Expires = DateTime.Now.AddDays(10)

 

5) Comment out the line above. We will write the same statement as above with a different syntax.Type the following lines of code in the Page_Load routine

 

 Dim mycookie As HttpCookie = New HttpCookie("mydata")
mycookie.Values("LastVisit") = DateTime.Now.ToString()
mycookie.Values("username") = "fofo"
mycookie.Expires = DateTime.Now.AddDays(10)
Response.Cookies.Add(mycookie)

6) Another thing we can do with the cookies is to specify the scope of the cookie. For example we might want to have a cookie stored on the user's computer only

if the user visits a specific folder-page e.g Marketing. So if someone visits www.mysite.com the cookie is not visible, but if he visits www.mysite.com/marketing and all pages within that folder the cookie is visible.

In order to achieve that we use the Path property to restrict the cookie to a particular path to a website.Comment out the lines above and type the following

Dim mycookie As HttpCookie = New HttpCookie("mydata")

        mycookie.Values("LastVisit") = DateTime.Now.ToString()
        mycookie.Values("username") = "fofo"
        mycookie.Expires = DateTime.Now.AddDays(10)
        mycookie.Path = "/Marketing"
        Response.Cookies.Add(mycookie)

 

 7) Another property we can use is the Domain property. So in the previous example we can comment out the

 mycookie.Path = "/Marketing"

and type

mycookie.Domain = "help.mysite.com"

This cookie will only be sent back to the server is the page is associated with the domain "help.mysite.com"

 8) In order to read cookies sent through the user's browser back to the server we do the following.

First you need to add a label web server control to your default.aspx page. Then in the Page_Load event handling routine type

  If Not Request.Cookies("LastVisit"Is Nothing Then

            Label1.Text = Server.HtmlEncode(Request.Cookies("LastVisit").Value)

        End If

9) Run you application and you will see that you successfully set a cookie and read it back from the user's computer.

10) If you want to modify the cookie's value and expiration date you can type something like

Response.Cookies("LastVisit").Value = DateTime.Now.ToString()
Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(30)

The code above will reset the value of "LastVisit" to the actual current time and set a new expiration date for the cookie

11) If you want to delete a cookie from the user's computer you can type the following

 Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(-1)

Then the browser will delete the cookie from the user's  computer.

If you need the source code just email me.

Hope it helps!!!

 

 

5 Comments

  • It's worth pointing out that you need to be *extremely* careful with the case of your cookie names. ASP.NET treats cookie names as case-insensitive, but most browsers treat them as case-sensitive.

    For example, if one page creates a cookie called "LastVisit" and another page creates a cookie called "lastVISIT", the browser will treat them as separate cookies. Whichever case you pass to the ASP.NET Cookies collection indexer, you'll get the value of the cookie the browser sent first in the request headers. This can lead to some confusion, where the value you set is lost on the next request, or the cookie you've just deleted reappears.

    It's a good idea to store cookie names as constants to ensure that the names are cased consistently. A better option would be to use a façade for any cookie access.

  • Hi can we store object in the cookies?

  • @vishal:i would advise against that. there are limitations.read this
    http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/100902-1.aspx

  • Very informative post. It’s really helpful for me and helped me lot to complete my task. Thanks for sharing with us. I had found another nice post over the internet which was also explained very well about How to read and write Cookies in asp.Net, for more details of this post check out this link…

    http://mindstick.com/Articles/60de760f-be8e-4ad8-8ec8-207aef746ea1/?How%20to%20read%20and%20write%20Cookies%20in%20ASP.Net

    Thanks

  • Just FYI, regarding cookie case sensitivity.
    I went through this a few months back. Cookies are case sensitive, but in ASP.NET you have loop through cookies that come through as a list\array or in Classic ASP you are out of luck.
    You can read a small article I wrote about this.
    http://www.daxmax.com/index.php/2012/05/01/cookie-names-are-case-sensitive/

Comments have been disabled for this content.