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

Cookies in ASP.NET

, 26 Aug 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
In this quick post, you will learn all about cookies used in web based applications.


Cookies are also known by many names, HTTP Cookie, Web Cookie, Browser Cookie, Session Cookie, etc. Cookies are one of several ways to store data about web site visitors during the time when web server and browser are not connected. Common use of cookies is to remember users between visits. Practically, cookie is a small text file sent by web server and saved by web browser on client machine.

Use of Cookies?

Cookies may be used for authentication, identification of a user session, user's preferences, shopping cart contents, or anything else that can be accomplished through storing text data. Cookies can also be used for travelling of data from one page to another.

Is Cookies Secured?

Well, this question has no specific answers in YES or NO. Cookies could be stolen by hackers to gain access to a victim's web account. Even cookies are not software and they cannot be programmed like normal executable applications. Cookies cannot carry viruses and cannot install malware on the host computer. However, they can be used by spyware to track user's browsing activities.

Using Cookies

Creating/Writing Cookies

There are many ways to create cookies, I am going to outline some of them below:

Way 1 (by using HttpCookies class)

//First Way
HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = TextBox1.Text;
StudentCookies.Expires = DateTime.Now.AddHours(1);

Way 2 (by using Response directly)

//Second Way
Response.Cookies["StudentCookies"].Value = TextBox1.Text;
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);

Way 3 (multiple values in same cookie)

//Writing Multiple values in single cookie
Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1); 

Reading/Getting Cookies

In the above code, I have used many ways to write or create cookies so I need to write here using all the above ways separately.

For Way 1

string roll = Request.Cookies["StudentCookies"].Value; //For First Way

For Way 2

string roll = Request.Cookies["StudentCookies"].Value;  //For Second Way

For Way 3

//For Multiple values in single cookie
string roll;
roll = Request.Cookies["StudentCookies"]["RollNumber"];
roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["MiddleName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["LastName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["TotalMarks"];
Label1.Text = roll; 

Deleting Cookies

In the above code, I have used many ways to create or read cookies. Now look at the code given below which will delete cookies.

if (Request.Cookies["StudentCookies"] != null)
    Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);
    Response.Redirect("Result.aspx");  //to refresh the page

Understanding HttpCookie Class It contains a collection of all cookie values.

We do not need to use any extra namespaces for HttpCookies class (we already have used this in Way 1 above), because this class is derived from System.Web namespaces. HttpCookies class lets us work with cookies without using Response and Request objects (we have already used this in Way 2 and Way 3 above).


HttpCookie class has a list of some properties, let us outline them.

  • Domain: It contains the domain of the cookie.
  • Expires: It contains the expiration time of the cookie.
  • HasKeys: It contains True if the cookie has subkeys.
  • Name: It contains the name of the cookie.
  • Path: It contains the virtual path to submit with the cookie.
  • Secure: It contains True if the cookie is to be passed in a secure connection only.
  • Value: It contains the value of the cookie.
  • Values:

Limitations of Cookies

There are following limitations for cookies:

  1. Size of cookies is limited to 4096 bytes.
  2. Total 20 cookies can be used on a single website; if you exceed this browser will delete older cookies.
  3. End user can stop accepting cookies by browsers, so it is recommended to check the users’ state and prompt the user to enable cookies.

Sometimes, the end user disables the cookies on browser and sometimes browser has no such feature to accept cookies. In such cases, you need to check the users’ browser at the home page of website and display the appropriate message or redirect on appropriate page having such message to enable it first. The following code will check whether the users’ browser supports cookies or not. It will also detect if it is disabled too.

protected void Page_Load(object sender, EventArgs e)
    if (Request.Browser.Cookies)
        //supports the cookies
        //not supports the cookies
        //redirect user on specific page
        //for this or show messages

It is always recommended not to store sensitive information in cookies.

Download the sample code attached with this post to check it yourself.

So, that is all about the ASP.NET cookies. Please post your feedback.


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


About the Author

Abhimanyu Kumar Vatsa
India India
Abhimanyu Kumar Vatsa (Abhimanyu Kumar Singh) is a Microsoft MVP and Mindcracker (C# Corner) MVP (2010, 2011) and having experience in building web scale applications using Microsoft Technologies including ASP.NET, MVC, C#/VB, jQuery, JavaScript, Silverlight, SQL Server and many more web stuffs. He is also handy in non-Microsoft Technologies like PHP, ColdFusion etc but he’s specility is always Microsoft. He love to work with Internet scale projects using Microsoft stuffs that has potential to change the every day use of technology. He love to blog and started it around June 2009 and because such blogging Microsoft awarded him MVP.
Follow on   Twitter

Comments and Discussions

GeneralVery Nice Pinmembervickycode418-Dec-14 1:51 
QuestionMy vote of 5 PinmemberAsım Ölmez16-Oct-14 22:40 
Generalgood work PinmemberRaza Syed10-Sep-14 2:43 
GeneralHow to Create and Read Cookies In ASP.NET Using C# PinmemberBinu198514-Jun-14 7:20 
QuestionHow to use cookies for storing multiple cart product and retrive them in shopping website Pinprofessionalgrvgarg25-Apr-14 13:27 
GeneralMy vote of 3 Pinmemberabhishek123456725-Feb-14 8:45 
Question5 PinmemberRonak Dey1-Jan-14 20:05 
GeneralSimple and Clear Pinmember VICK23-Oct-13 19:35 
GeneralMy vote of 5 PinmemberBritteandy26-Sep-13 2:58 
GeneralMy vote of 5 PinmemberMember 770584528-Jul-13 20:53 
GeneralMy vote of 5 PinmemberLê Xuân Tiến26-May-13 20:16 
GeneralMy vote of 5 PinmemberАslam Iqbal19-May-13 1:13 
GeneralMy vote of 5 Pinmembermdogggg25-Apr-13 2:08 
GeneralThanx bro.Really very nice and simple explanation about cookies.It helps me a lot. :) PinmemberTushar Kanti Das9-Apr-13 0:38 
GeneralMy vote of 5 PinmemberAlireza_13624-Apr-13 17:18 
GeneralMy vote of 5 PinmemberAzziet12-Mar-13 21:06 
GeneralMy vote of 5 Pinmembercsharpbd12-Mar-13 0:57 
Questionmy vote 5 PinmemberNitin Sawant12-Mar-13 0:51 
SuggestionNice but need more information on cookies... Pinmemberrajneeshrai28-Feb-13 20:13 
SuggestionRe: Nice but need more information on cookies... PinmemberVasudevan Deepak Kumar4-Apr-13 7:48 
GeneralMy vote of 5 PinmemberVitorHugoGarcia22-Feb-13 4:25 
Questioncookie acceptance code in asp & Pinmembersatya muntha17-Jan-13 5:46 
SuggestionThanks Pinmemberaspplus6-Jan-13 13:27 
GeneralMy vote of 4 Pinmemberzhxhdean21-Oct-12 21:06 
GeneralMy vote of 4 PinmemberEng_kashi24-Sep-12 20:19 
GeneralAbout ur article Pinmembermohan.miriyala6-Sep-12 9:30 
Questionnice artical Pinmembersandeep nagabhairava6-Aug-12 1:10 
GeneralMy vote of 5 Pinmemberzhxhdean12-Jul-12 21:37 
Questionvery informative PinmemberMember 773967311-Jul-12 8:29 
GeneralMy vote of 5 Pinmemberramanakamma18-Jun-12 19:32 
Questionpls its urgent PinmemberPriya Paapu23-Apr-12 18:58 
GeneralMy vote of 5 PinmemberMember 832439327-Feb-12 6:23 
GeneralMy vote of 5 PinmemberSunil Mane 00714-Feb-12 22:37 
QuestionFile download is corrupt and won't open with winzip or explore. Pinmembersma77714-Feb-12 6:29 
GeneralMy vote of 5 PinmemberMuthukrish5916-Jan-12 6:46 
GeneralMy vote of 5 Pinmemberzerocool185-Nov-11 19:21 
GeneralMy vote of 5 Pinmemberirritaldo3-Oct-11 2:48 
QuestionWay 1 and 2 for reading cookies PinmemberBrianBissell1-Sep-11 10:50 
GeneralMy vote of 5 PinmemberBrianBissell1-Sep-11 10:48 
GeneralMy vote of 4 PinmemberSREENATH.G1-Sep-11 9:29 
QuestionThe link for the download didn't work PinmemberGer F.30-Aug-11 23:32 
GeneralMy vote of 4 Pinmembergerm1330-Aug-11 20:13 
QuestionReading Cookies through Response Pinmembertaloweb26-Aug-11 23:24 
GeneralCookie limitations PinmentorDaveAuld26-Aug-11 2:23 
GeneralRe: Cookie limitations PinmemberAbhimanyu Kumar Vatsa26-Aug-11 5:33 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 26 Aug 2011
Article Copyright 2011 by Abhimanyu Kumar Vatsa
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid