Maintaining client data with cookies in ASP.NET

Cookies are one of the methods that ASP.NET provides for storing user-specific data. While you shouldn't use cookies to store sensitive data, find out why they're an excellent choice for more trivial data such as color preferences and last-visit date.

Cookies provide a useful means in Web applications to store user-specific information. JavaScript developers have been doing the bulk of cookie-related work for many years. ASP.NET also provides cookie access through the System.Web namespace. While you shouldn't use cookies to store sensitive data, they're an excellent choice for more trivial data such as color preferences or last-visit date.

Pass the cookies

Cookies are small files stored on the client computer. If you're a Windows user, examine the Cookies directory in your user directory, which is within the Documents And Settings directory. This directory contains text files with this filename format:

username @ Web site domain that created the cookie

The text files may contain name/value pairs, separated by an equal sign, along with more information. Let's turn our attention to working with these files in ASP.NET.

Cookie interaction in ASP.NET

The .NET System.Web namespace has three classes that you can use to work with client-side cookies:

  • HttpCookie: provides a type-safe way to create and manipulate individual HTTP cookies.
  • HttpResponse: The Cookies property allows client cookies to be manipulated.
  • HttpRequest: The Cookies property allows access to cookies that the client maintains.

The Cookies property of both the HttpResponse and HttpRequest objects returns an HttpCookieCollection object. It has methods to add and retrieve individual cookies to and from the collection.

HttpCookie class

The HttpCookie class allows individual cookies to be created for client storage. Once the HttpCookie object is created and populated, you can add it to the Cookies property of the HttpResponse object. Likewise, you can access existing cookies via the HttpRequest object. The HttpCookie class contains the following public properties:

  • Domain: Gets or sets the domain associated with the cookie. This may be used to limit cookie access to the specified domain.
  • Expires: Gets or sets the expiration date and time for the cookie. You may set this to a past date to automatically expire or delete the cookie.
  • Names: Gets or sets the cookie name.
  • Path: Gets or sets the cookie's virtual path. This allows you to limit the cookie's scope; that is, access to the cookie may be limited to a specific folder or directory. Setting this property limits its access to the specified directory and all directories beneath it.
  • Secure: Signals whether the cookie value is transmitted using Secure Sockets Layer (SSL).
  • Value: Gets or sets an individual cookie value.
  • Values: Retrieves a collection of key/value pairs contained within the cookie.

While this isn't an exhaustive list, it provides everything you need to work with cookies. A VB.NET example will give you a better idea of how it works:

Dim testCookie As New HttpCookie("LastVisited")
testCookie.Value = DateTime.Now.ToString
testCookie.Expires = DateTime.Now.AddDays(7)
testCookie.Domain = ""

This code creates a new cookie with the name LastVisited and populates the value with today's date and time. Also, the cookie expiration is set to one week, and the associated domain is populated. Once the object is created, it's added to the client's cookies collection via the Response.Cookies object's Add method. The HttpCookie constructor method has two variations:

  • HttpCookie objectName = New HttpCookie("cookieName")
  • HttpCookie objectName = New HttpCookie("cookieName", "cookieValue")

Also, the Response object contains a SetCookie method that accepts an HttpCookie object.

Where's my cookie?

Once cookies are stored on the client, there are various ways that you can access them. If you know the cookie name, you can easily access its value(s) with the HttpResponse object. The following VB.NET line displays the value associated with the cookie:


In addition, the complete list of cookies may be accessed via an HttpCookieCollection object. This allows the cookie list to be processed with a for loop. The following C# code provides a sample:

HttpCookieCollection cookies;
HttpCookie oneCookie;
cookies = Request.Cookies;
string[] cookieArray = cookies.AllKeys;
for (int i=0; I < cookieArray.Length; i++) {
oneCookie = cookies[cookieArray[i]];
Response.Write(oneCookie.Name + " - " + oneCookie.Value);

Here's the same code in VB.NET:

Dim i As Integer
Dim oneCookie As HttpCookie
For i = 0 To Request.Cookies.Count - 1
oneCookie = Request.Cookies(i)
Response.Write(oneCookie.Name + " - " + oneCookie.Value)
Next I

Stability is an issue

The cookie files are stored on the client machine, so your users can delete or edit them at any time. In addition, some users may disable cookies. For this reason, never rely on that data. You should store critical information on the server—preferably in a database. Also, you should use cookies only for minor information that may customize the user experience.

Storing critical information in a cookie is considered poor programming because it can be viewed easily, since it resides in a file on the client machine. One way around this is to use SSL; a better approach is to avoid cookies with sensitive information.

Can I use cookies?

Users may disable cookie support in their browser. You can access this setting in your code to determine if cookies are supported. The Request object makes this determination easy. The following VB.NET code shows how it's used:

If Request.Browser.Cookies = True Then
' Work with cookies
' No cookie support
End If

This may be combined with code to utilize cookie values. The following C# code snippet tests for cookie support and populates a text box control accordingly (whether a cookie is present or not):

if (Request.Browser.Cookies == true)
if (Request.Cookies["LastVisited1"] == null)
HttpCookie newCookie = new HttpCookie("LastVisited1",DateTime.Now.ToString());
newCookie.Expires = DateTime.Now.AddYears(1);
this.txtName.Text = "Is this your first time?";
} else {
this.txtName.Text = "We haven't seen you since " +
}  }

You could place this code in the Page_Load event of an ASP.NET page.

Another way to store data

ASP.NET provides several methods for storing user-specific data. One of the older methods is cookies. While cookies aren't the best vehicle for sensitive data, they're an excellent choice for benign items such as color preferences, last-visit date, and so forth. While this data is important, it isn't the end of the world if it's lost when the user's computer crashes.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks

Free Newsletters, In your Inbox