Click here to Skip to main content
Click here to Skip to main content

Beginner's Guide to ASP.NET Cookies

By , 29 Dec 2008
 

Table of Contents

Introduction

First of all, I would like to thank all of the readers who have read my previous articles and voted for me. Wow.. what a great support I have got from you people. Again, thanks to Sean Ewington for starting up a very fantastic idea with the Beginner's Walk for Web Development article. I have written a few articles for beginners. I really felt great when my Beginner's Guide to ViewState article was displayed on the CodeProject Home page Editor's Choice section. Following are the articles that I have written so far for beginners.

Cookies, Session, and Application object are in my queue. Now it's time for learning about cookies. I have spent a lot of time to prepare this article. And you will be very surprised to know that the Introduction part is the last topic which I am writing before posting the article. I have read many articles, books before writing this article. I have done some hands on projects also. Hope I have explained this well and I hope you people will like it. Please give your suggestions and feedback.

What are Cookies?

Cookies are the small files that are created on the client's system or client browser memory (if temporary). It is used for state management which I have already discussed in my ViewState article. We can store small pieces of information in a client system and use it when needed. The most interesting thing is that it works transparently with the user. It can be easily used anywhere in your web application. Cookies store information in plain text format. If a web application uses cookies, the server sends cookies and the client browser will store it. The browser then returns the cookie to the server the next time the page is requested. The most common examples of using a cookie are to store user information, user preferences, password remember option, etc. Cookies have many advantages and disadvantages. I will come to this later on, but first, have a look at how cookies are started.

How are Cookies started?

When a client requests to the server, the server sends cookies to the client. The same cookies can be referred to for subsequent requests. For example, if codeproject.com stores the session ID as cookies, when a client hits the first time on the server, the server generates the session ID and sends it as a cookie to the client [as shown in Fig. 1.0.].

Cookie1.jpg

Fig. 1.0: Initial state of cookie creation

Now for all subsequent requests from the same client, it uses the session-ID from the cookies, just like in the picture below:

Cookie2.jpg

Fig. 1.1: Subsequent request for other pages

The browser and web server are responsible for exchanging cookies information. For different sites, the browser keeps cookies differently. If a page needs information from the cookies, when that URL is hit, first it searches the local system for cookies information, then it is moved to the server with that information.

Advantages of Cookies

Following are the main advantages of using cookies in a web application:

  • It's very simple to use and implement.
  • Browser takes care of sending the data.
  • For multiple sites with cookies, the browser automatically arranges them.

Disadvantages of Cookies

The main disadvantages of cookies are:

  • It stores data in simple text format, so it's not secure at all.
  • There is a size limit for cookies data (4096 bytes / 4KB).
  • The maximum number of cookies allowed is also limited. Most browsers provide limits the number of cookies to 20. If new cookies come, the old ones are discarded. Some browsers support up to 300.
  • We need to configure the browser. Cookies will not work on a high security configuration of the browser. [I have explained this in details.]

How to create Cookies

For working with cookies, we need to use the namespace System.web.

Cookie3.gif

Have a look at the code and see how we create cookies and add it with a web response.

Cookie4.gif

The cookies which have been created will persist until the browser is closed. We can persist cookies beyond that. But how? I have explained this below.

How to read data from Cookies

Now it is time to retrieve data from the cookies. Before reading the cookies, first we need to check whether a cookie was found or not. It is always a good practice to check a cookie before reading it, because the browser might have disabled cookies.

Cookie7.gif

What are persistent and non-persistent Cookies?

We can classify cookies into two:

  • Persistent Cookies
  • Non-persistent Cookies

Persistent cookies: These can be called permanent cookies, which are stored in the client hard-drive until they expire. Persistent cookies should be set with an expiration dates. Sometimes thet stays until the user deletes the cookies. Persistent cookies are used to collect identification information about a user from the system. I have discussde about the creation of persistent cookies in the "How to make persistant Cookies" section.

Non-persistent Cookies: These can be called temporary Cookies. If there is no expiration time defined, then the cookie is stored in the browser memory. The example which I have shown above is a non-persistent cookie.

There is no difference between modifying a persistent and non-persistent cookie. The only difference between them is persistent cookies should have an expatriation time defined.

How to make persistent Cookies?

I have already given an example of non-persistent cookies. For persistent cookies, we need to add an expiration time. In the given code, I have specified 5 days.

//Creting a Cookie Object
HttpCookie _userInfoCookies = new HttpCookie("UserInfo");

//Setting values inside it
_userInfoCookies["UserName"] = "Abhijit";
_userInfoCookies["UserColor"] = "Red";
_userInfoCookies["Expire"] = "5 Days";

//Adding Expire Time of cookies
 _userInfoCookies.Expires = DateTime.Now.AddDays(5);

//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);

The most interesting thing is where they are stored in the hard drive.

Where are Cookies stored in the local hard drive?

This is one of the interesting things to know to find out cookies in your local drive. First of all, from Explorer Folder Options, select show hidden files and folders.

Cookie8.jpg

Fig 1.2 : Show Hidden files and Folders settings

Now browse into Documents & Settings of the current user and open the cookies folder. Take a look at this picture.

Cookie9.jpg

Fig 1.3 : Reading Cookies info in the local System

How to remove persistent Cookies before its expiration time?

This is a funny task. If you want to remove persistent cookies before the expiration date, the only way is to replace them with cookies with a past expiration date.

HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
//Adding Expire Time of cookies before existing cookies time
_userInfoCookies.Expires = DateTime.Now.AddDays(-1);
//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);

How to control Cookies scope?

We can controll the scope of cookies the following ways:

  • Limiting Cookies to Path
  • Limiting Cookies Domain

What is Cookie Munging?

By default, ASP.NET uses cookies to stores session IDs, but as I have already mentioned, some browser do not support cookies. To overcome this problem, ASP.NET uses "Cookie Munging" to manage session variables without cookies.

[Though this is related with Session, I am just giving a basic overview. I will explain this in detail in my next article which will be on Session.]

Why are we using Cookie Munging in ASP.NET?

There are some specific reasons to use cookie munging in ASP.NET:

  • Some browsers do not support cookies.
  • Sometimes users disable cookies in the browser.

How Cookie Munging works

When the user requests for a page on the server, the server encodes the session ID and adds it with every HREF link in the page. When user click on a link, ASP.NET decodes that session ID and passes it to the page that the user has requested. Now the requesting page can retrieve any session variable. This all happens automatically if ASP.NET detects that the user's browser does not support cookies.

Cookie10.jpg

Fig .1.4 : Steps of Cookie Munging

How to implement Cookie Munging

For this, we have to make session state cookie-less.

<sessionState cookieless= "true />

I am stopping here on this topic. I will explain it in detail when I write an article on Session.

How to configure Cookies in the browser

We can now take a look at how we can configure the browser for enabling/disabling cookies. I have already discussed about settings in the IE browser. Click on Tools -> Internet Options -> go to Privacy tab. There you will be able to see a scroll bar with the following options:

  • Accept All Cookies
  • Low
  • Medium
  • Medium High
  • Block All Cookies

Test.gif

The first option will accept all cookies and the last option will block all cookies. You can get the details of those settings while scrolling the bar.

Summary

There are many topics to learn about cookies. I have covered just a small portion. Hope this will help all beginners to get familiar with cookies. Please give your feedback and suggestions.

History

  • Written on 20-Dec-08, Saturday.
  • Updated info on browser configuration: 22-Dec-08.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Abhijit Jana
Software Developer (Senior)
India India
Member
.NET Consultant | Former Microsoft MVP - ASP.NET | CodeProject MVP, Mentor, Insiders| Technology Evangelist | Author | Speaker | Geek | Blogger | Husband
 
Blog : http://abhijitjana.net
Web Site : http://dailydotnettips.com
Twitter : @AbhijitJana
My Kinect Book : Kinect for Windows SDK Programming Guide

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberChinmayasri Behera12 Apr '13 - 6:07 
Really nice article for a beginner.
Helped a lot.
GeneralMy vote of 5memberAkiii00121 Feb '13 - 15:18 
excellent article
GeneralMy vote of 5memberRajaPrabu29 Jan '13 - 17:58 
Clear and good explanation.. Great work
GeneralMy vote of 5memberffowler8 Jan '13 - 8:28 
Clear, concise and well published. Thank you for the quick start.
SuggestionThanksmemberaspplus6 Jan '13 - 12:26 
was very helpful Thumbs Up | :thumbsup:
GeneralMy vote of 5memberVelkumar Kannan30 Oct '12 - 18:03 
Nice. Its useful for all
GeneralMy vote of 5membervikashSrivastava10 Sep '12 - 2:31 
eay to under stand
QuestionPersistent cookies share the session between tabs?memberjeyamothi3 Sep '12 - 21:29 
Hi,
 
Your article is helpful for me. Is the persistent cookies shares their session between tabs?
GeneralMy vote of 3memberAnkit Kumar24 Aug '12 - 20:31 
good job man!!
GeneralMy vote of 5memberTapan Kumar Sundaray20 Aug '12 - 19:54 
Very nice
GeneralthanksmemberAmani Hussein5 Aug '12 - 9:03 
Actually i'm sooo glad from u it's sooo helpfull artical , i searched about session and application articals for u but i didn'y find any thing can u send the link for them if u made it plz ?...
my regards ...
GeneralMy vote of 5memberSoMad10 Jul '12 - 16:47 
This is a great article, you did a very good job.
 
Soren Madsen
QuestionMissinformation in your articlememberqinta19 Jun '12 - 23:49 
If the session is set to cookieless the SessionID is kept in the URL, not in the hrefs on the page. If you share the URL with someone, then he has access to your session.
GeneralBeginner's Guide to ASP.NET Cookiesmembersara000079 Jun '12 - 9:03 
Max! Thank you sir,! This is a greate explanation about cookies
Shanaka from ngbr (Sri Lanka) Wink | ;)
Questionthank u sirmembermanghal7 Jun '12 - 0:02 
sir this is very great article to understand cookie and i want an article on polymorphism in detail like this .............
 

if there is possibility then please send me mail mangalgupta.43212gmail.com
GeneralMy vote of 5memberAlireza_13626 May '12 - 6:16 
Thanks in advanced ,please write article about Master Pages
GeneralMy vote of 5memberbaihualin19834 Apr '12 - 17:45 
I'm a beginer at asp.net,It helps me a lot.Thanks.
QuestionThanksmemberkeivan_tar10 Mar '12 - 23:19 
Hi mr author .
I found your article so useful.Actually I am almost an amateur in programming and i am interested in learning news.Thanks for your integrated article and we all anticipate your nest articles.
thank you,keivan
QuestionGood ArticlememberAnanthikasivel24 Jan '12 - 22:40 
Very useful article to understand cookies concept in asp.net .My vote is 5
GeneralMy vote of 4memberTamiruD29 Dec '11 - 20:46 
simple and enough information
GeneralMy vote of 4memberItz.Irshad7 Dec '11 - 21:12 
Hi,
Nice work Abhijit.
Keep it up !
GeneralMy vote of 5 [modified]memberPrince Antony G28 Nov '11 - 17:40 
Hi have tried this but its not working for me kindly help me out in this process so that i can understand more about cookies

modified 29 Nov '11 - 1:51.

GeneralMy vote of 5memberReza Mansoori25 Nov '11 - 22:20 
very Good , But Not Complete
GeneralMy vote of 5memberUday P.Singh21 Nov '11 - 7:46 
Very well written, Excellent! Laugh | :laugh:
GeneralMy vote of 5memberfcis20102 Sep '11 - 13:19 
good

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 29 Dec 2008
Article Copyright 2008 by Abhijit Jana
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid