Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book


The QueryString and Form collections are available for each browser request, and result from parameters and/or submitted forms from the previous page. Each time the user requests any file from the server, the Request object's collections are updated with the information from the request. Occasionally you may find a need for more persistent data storage. To achieve this, the concept of cookies was introduced into the HTTP protocol specification, and quickly adopted by the browsers.

A cookie is a packet of information that is sent by the browser to the server with each request. Data items within each cookie are available in the Cookies collection, and it is accessed in a similar manner to the QueryString and Form collections. The cookie is stored as a file on the client machine, which means that it can be used to store information that is available the next time the browser starts.

When accessed through the Request object, the cookies are read-only because the information they represent is actually held on the client browser, and not the server. You can change cookie information only by using the Response object (see Chapter 4).

ASP.NET introduced two classes that help you deal with cookies. They are HttpCookieColection and HttpCookie. They are used in the next example.

To access cookies, first retrieve the cookie collection as follows:

Dim objCookieColl As HttpCookieCollection
objCookieColl = Request.Cookies

Then, to retrieve each individual cookie, use the following code:

objThisCookie = objCookieColl( "CookieName" )

The following code enumerates all cookies that currently exist for the current session and displays them in the HTML document:

 Dim Loop1, Loop2 As Integer
 Dim Array1(), Array2() As String
 Dim objCookieColl As HttpCookieCollection
 Dim objThisCookie As HttpCookie

 objCookieColl = Request.Cookies
 Array1 = objCookieColl.AllKeys
 for Loop1 = 0 To UBound( Array1 )
 objThisCookie = objCookieColl( Array1( Loop1 ) )
 Response.Write( "Cookie: " & objThisCookie.Name & "<br>" )
 Response.Write( "Expires: " & objThisCookie.Expires & "<br>" )
 Response.Write( "Secure:" & objThisCookie.Secure & "<br>" )

 Array2 = objThisCookie.Values.All
 for Loop2 = 0 To UBound( Array2 )
  Response.Write( "Value " & CStr(Loop2) + ": " & Array2(Loop2) & "<br>" )
 Next Loop2

 Next Loop1


This code is part of the page that you can find at http://www.UsingASP.net, selecting Chapter Examples, Chapter 3, then Cookies. You can see the rendered page in Figure 3.16.

Figure 3.16 Enumerating the Cookie collection shows the current set of cookies.

  • + Share This
  • 🔖 Save To Your Account