Create and Read Cookies...
By: John Kilgo Date: December 12, 2002 Download the code.


In this article we will see how to determine if a user's browser accepts cookies, how to create both session and persistent cookies, how to read cookies, and how to store and read cookies with sub-keys (cookie dictionary). First, the .aspx page, which is mostly labels and explanations of what the program displays.
<%@ Page Language="vb" src="HaveSomeCookies.aspx.vb" Inherits="HaveSomeCookies" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>RequestObject</title>
</head>
<body>
<asp:Label ID="lblCookiesAllowed" Runat="server" />
<h4>You are storing the following cookies:</h4>
<asp:Label ID="lblHaveCookies" Runat="server" />
<p>
The <b>"ASP.NET_Sessionid"</b> and <b>"aCookie"</b> are session cookies and will
expire when this asp.net session expires. Any other cookies you see are persistent
cookies and will expire at some future date.
</p>
<p>
The following "favorites" cookie contains a dictionary. You may also see this referred
to as a cookie with sub-keys. It is a cookie with multiple item-value pairs. If you
click your browser's refresh (or reload) button you will see the favorites cookie above
in the state in which it is stored.
</p>
<p>
<asp:Label ID="lblSubsCookie" Runat="server" />
</p>
</body>
</html>
Now for the code-behind file which does all of the work for this page. First the Namespace Imports.
Imports System
Imports System.DateTime
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.Page
Imports System.Web.UI.WebControls
Next comes the main class declaration and the dimensioning of variables and cookie objects in the Page_Load event where all the work is done. Since the first thing we want to do is check to see if your browser accepts cookies we create an HttpBrowserCapabilities object. We also create several HttpCookie objects for the cookies we will create (assuming you allow cookies).
Public Class HaveSomeCookies : Inherits Page
  Protected WithEvents lblCookiesAllowed As Label
  Protected WithEvents lblHaveCookies As Label
  Protected WithEvents lblSubsCookie As Label

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim objBrowsCap As HttpBrowserCapabilities
    Dim objSessionCookie As New HttpCookie("aCookie", "This is a cookie value")
    Dim objPersistCookie As New HttpCookie("PersistentCookie", "This expires tomorrow")
    Dim objSubsCookie As New HttpCookie("Favorites")
    Dim strKey As String
    Dim strItem As String
    Dim blnCookies As Boolean
Now we view the remainder of the Page_Load event where we are writing and reading our cookies. First we determine if your browser allows cookies. The rest of the program is moot if you are not allowing cookies. We set objBrowsCap equal to Request.Browser to gather data from the browser. We can then access the Cookies property (a boolean) to make sure that your browser is allowing cookies. We write the results to a label and set a boolean variable to be used to avoid errors if cookies are not allowed.

After that we use the Response object to add a session cookie defined at the top of the Page_Load event. After that we add a persistent cookie. We use the DateTime namespace (Now) to set an expiration date of tomorrow.

Next we use a For Each loop to test for cookies that presently exist on your machine. We write the key - values pairs to a label control. When you run the program you will see that at least one cookie exists that we did not specifically create. .Net automatically writes a SessionID cookie to your machine to keep track of you separately from anyone else using this web site. We use the .Values (plural) property to set the multiple key-value pairs for this cookie. Notice that when we read the cookie with sub-keys, we use the HasKeys property of the cookie object.

Lastly, we add and then read a cookie with a dictionary (or sub-keys if you prefer). Notice that we check the HasKeys property before reading in the key-value pairs.

    'Determine if cookies are accepted
    objBrowsCap = Request.Browser
    If objBrowsCap.Cookies Then
      lblCookiesAllowed.Text = "Your Browser Supports Cookies!"
      blnCookies = "True"
    Else
      lblCookiesAllowed.Text = "Your Browser Does Not Support Cookies!"
    End If

    'Add a Session Cookie
    If blnCookies Then
      Response.Cookies.Add(objSessionCookie)
    End If

    'Add a Persistent Cookie
    If blnCookies Then
      objPersistCookie.Expires = now.AddDays(1)
      Response.Cookies.Add(objPersistCookie)
    End If

    'Show All Cookies
    If blnCookies Then
      For Each strKey in Request.Cookies
        lblHaveCookies.Text &= "<li>" & strKey & "=" & Request.Cookies(strKey).Value
      Next
    End If

    'Create a Cookie with Sub Keys (Dictionary)
    If blnCookies Then
      objSubsCookie.Values("team") = "Yankees"
      objSubsCookie.Values("color") = "Blue"
      objSubsCookie.Values("hair") = "Blond"
      objSubsCookie.Values("car") = "Ford"
      Response.Cookies.Add(objSubsCookie)
    End If

    'Now Read the Sub-Keys (Dictionary) Cookie
    If blnCookies Then
      IF objSubsCookie.HasKeys Then
        For Each strItem in objSubsCookie.Values
          lblSubsCookie.Text &= "<li>" & strItem & "=" & objSubsCookie.Values(strItem)
        Next
      End If
    End If

  End Sub
End Class

You may download the code by clicking Here.