Saturday, September 27, 2008

Cookie in ASP.NET

The HTTP protocol, the fundamental protocol of the World Wide Web, is a stateless protocol. What this means is that from a web server’s perspective, every request is from a new user.


  • You can create two types of cookies:
    • Session Cookie:
      • Exists only in memory.
      • Disappears when browser is closed.
      • If you do not specify an expiration date for the newly created cookie, then it will become a session cookie.
    • Persistent Cookie:
      • IE stores cookies in: \Documents and Settings\[user]\Cookies
      • FireFox stores cookies in: \Documents and Settings\[user]\Application Data\Mozilla\Firefox\Profiles\[random folder name]\Cookies.txt
  • Browser Relative
    • Cookies created by IE will not be recognised by FireFox.
  • Stored in Clear Text
    • You should never store sensitive information in a cookie.
  • Domain Relative
    • When a browser creates a cookie, the browser records the domain associated with the cookie and doesn’t send the cookie to another domain.
  • Cookie names are case sensitive.
  • Size
    • A single domain cannot store more than 4096 bytes which includes both the cookie names and the cookie values.
    • Most browsers restrict the number of cookies that can be set by a single domain to
      no more than 20 cookies (but not IE). If you attempt to set more than 20 cookies, the oldest cookies are automatically deleted. You can work around this limitation by creating multi-valued cookies.
  • Usage
    • Many parts of the ASP.NET Framework rely on cookies.
      • Web Parts
      • Forms Authentication
      • Session State
      • Anonymous Profiles
    • Many websites rely on cookies.
      • Yahoo
      • MSDN

Cookie Properties

  • Domain:
    • This property is useful when your organization includes subdomains.
    • Use this property to associate a cookie with a subdomain, but not an entirely different domain.
  • HttpOnly
    • Specify whether a cookie can be accessed from JavaScript code.
    • This property works only with Internet Explorer 6 (Service Pack 1) and above.
    • The property was introduced to help prevent cross-site scripting attacks.

Multi-Valued Cookies

  • A multi-valued cookie is a single cookie that contains subkeys. You can create as many subkeys as you need.
  • You can use the HttpCookie.HasKeys property to detect whether a cookie is a normal cookie or a multi-valued cookie.

Code Sample:

In the sample code, I will show you how to create, display and delete cookie.

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestCookie._Default" Trace="true"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >

<head runat="server">

<title>Untitled Page</title>



<form id="form1" runat="server">


<asp:Button ID="btnCreate" runat="server" Text="Create Cookie" />

<asp:Button ID="btnPostBack" runat="server" Text="Post Back" />

<asp:Button ID="btnDisplay" runat="server" Text="Display Cookie" />

<asp:Button ID="btnDelete" runat="server" Text="Delete Cookie" />

<asp:Button ID="btnCreateMultiValued" runat="server" Text="Create multi-valued Cookie" />

<asp:Button ID="btnDisplayMultiValued" runat="server" Text="Display multi-valued Cookie" />





Partial Public Class _Default

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Private Sub btnCreate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreate.Click

Response.Cookies("TestUserFirstName").Value = "Sam"

Response.Cookies("TestUserFirstName").Expires = DateTime.MaxValue

Response.Cookies("TestUserLastName").Value = "Fu"

Response.Cookies("TestUserLastName").Expires = DateTime.MaxValue

End Sub

Private Sub btnDisplay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDisplay.Click

For i As Integer = 0 To Request.Cookies.Count - 1

Response.Write(String.Format("{0}: {1}<br />", Request.Cookies(i).Name, Request.Cookies(i).Value))


If Request.Cookies("TestUserFirstName") IsNot Nothing Then

Response.Write("TestUserFirstName=" + Request.Cookies("TestUserFirstName").Value)

End If

If Request.Cookies("TestUserLastName") IsNot Nothing Then

Response.Write("TestUserLastName=" + Request.Cookies("TestUserLastName").Value)

End If

End Sub

Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click

Dim cookies As String() = Request.Cookies.AllKeys

For Each cookie As String In cookies

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


End Sub

Private Sub btnCreateMultiValued_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateMultiValued.Click

Response.Cookies("TestUser")("FirstName") = "Sam"

Response.Cookies("TestUser")("LastName") = "Fu"

Response.Cookies("TestUser").Expires = DateTime.MaxValue

End Sub

Private Sub btnDisplayMultiValued_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDisplayMultiValued.Click

If Request.Cookies("TestUser") IsNot Nothing Then



End If

End Sub

End Class


  • Request.Browser.Cookies will only check whether the browser support cookie, not whether or not they're enabled.

How it works

Step 1. Before any request.

Step 2. Click the create cookie button. The server send the response back with an additional HTTP header to the browser. The HTTP response header looks like this: Set-Cookie: TestUserFirstName=Sam. This Set-Cookie header causes the browser to create a cookie named TestUserFirstName that has the value Sam. The 'Headers Collection' of the tracing ouput is always the request header, not the response header, so you cannot see 'Set-Cookie' in this section.

Step 3. Click the postback button. After a cookie has been created on a browser, whenever the browser requests a page from the same application in the future, the browser sends a request header that looks like this:Cookie: TestUserFirstName=Sam. The Cookie header contains all the cookies that have been set by the web server.


  • There are two HTTP headers, Set-Cookie and Cookie, that are related to cookies.
    • Set-Cookie response header is sent by the server in response to an HTTP request, which is used to create a cookie on the user's system. (Refer to Step 2 above)
    • Cookie request header is included by the client application with an HTTP request sent to a server if there is a cookie that has a matching domain and path. (Refer to Step 3 above)


ASP.NET 2.0 Unleashed

Working with Cookies

blog comments powered by Disqus