Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Gauge for SharePoint
Search :       Advanced Search »
Home » Caching » Browser Cookies and ASP.NET

Browser Cookies and ASP.NET

This article explains how to create and delete browser cookies using ASP.NET.

Author Rank :
Page Views : 22608
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Browser cookies are used to store small pieces of information on a client machine. A cookie can store only up to 4 KB of information. Generally cookies are used to store data which user types frequently such as user id and password to login to a site.

There are two types of browser cookies - session and persistent. Session cookies, also called as temporary cookies are stored in a browsers memory and stay alive as long as a browser session is live. When you close a browser, these cookies die.

On the other hand, persistent cookies stored on the hard drive with a date information and can live for a long time. When you create persistent cookies, you specify a date as the life period of the cookie. Even though it's not certain that a cookie will live as long as you specify.

Even though cookies are useful object in Web development but they've some limitations. As we said earlier, you can't store large data in cookies. Cookies are also browser dependent, which means your cookies based application may not work in some browsers.

You can specify a life period of a cookie, but there is no guarantee a cookie will be available for that long time. So storing important information in cookies is not a good idea.

Creating and Reading Cookies

The HttpCookie class defined in the System.Web namespace represents a browser cookie. The Cookies property of the Response and Request classes can be used to read all cookies as a HttpCookieCollection object, which represents a collection of cookies. Like other collection classes, the HttpCookieCollection class provides members to add, remove, and read cookies from the collection.

You can create a cookie by using the HttpCookie class by passing cookie name and its value as string values as first and second arguments. Or you can also use the Name and Value properties of HttpCookie to set the name and values of a cookie. The Expires property of the HttpCookie class makes a cookie persistent and sets a date when a cookie will expire.

The code listed in Listing 1 creates two cookies "UID" and "PASS". As you can see from this code, we add cookies to the collection by using the Response.Cookies.Add method.

Listing 1. Creating cookies

' Create user id and password cookies
' set their values and add to the collection
Dim cookie As HttpCookie = New HttpCookie("UID")
cookie.Value = "myid"
cookie.Expires = #9/28/2002#
Response.Cookies.Add(cookie)
cookie =
New HttpCookie("PASS")
cookie.Value = "mypass"
cookie.Expires = #9/28/2002#
Response.Cookies.Add(cookie)

You can read cookies using the Request.Cookies property. The code listed in Listing 2 reeds the cookies from the browser and adds them to a ListBox control.

Listing 2. Reading cookies

' Read cookies
Dim cookieCols As New HttpCookieCollection
cookieCols = Request.Cookies
Dim str As String
' Read and add all cookies to the list box
For Each str In cookieCols
ListBox1.Items.Add("Cookie: " + str)
ListBox1.Items.Add("Value:" & _
Request.Cookies(str).Value)
Next

You can use the Remove and Clear methods of HttpCookieCollection  to remove a particular cookie by name or all cookies respectively. The code listed in Listing 3 delete the cookies using the Remove method.

Listing 3. Deleting cookies

Dim cookieCols As New HttpCookieCollection
cookieCols = Request.Cookies
Dim str As String
' Read and add all cookies to the list box
Request.Cookies.Remove("PASS")
Request.Cookies.Remove("UID")

A cookie can also store multiple values. This type of cookies called cookie dictionaries. You use Values property to create and read this type of cookies. The code listed in Listing 4 creates a dictionary cookie.

Listing 4. Creating a dictionary cookie

Dim cookDict As HttpCookie = New HttpCookie("dict")
cookDict.Values("fname") = "first name"
cookDict.Values("lname") = "last name"
cookDict.Values("Address") = "address"
Response.Cookies.Add(cookDict)

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
new to ASP.NET by Umer On July 30, 2011
dear mahesh i m new to asp.net and want to learn it... any suggestion, advice?
Reply | Email | Modify 
Re: new to ASP.NET by Mahesh On September 8, 2011
Asp.net website has lot of videos and tutorials.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.