Special Edition Using ASP.Net
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() as String Dim Array2 As NameValueCollection Dim objCookieColl As HttpCookieCollection Dim objThisCookie As HttpCookie objCookieColl = Request.Cookies Array1 = objCookieColl.AllKeys for Loop1 = 0 To Array1.Length - 1 objThisCookie = objCookieColl.Item( Array1( Loop1 ) ) Response.Write( "Cookie: " & objThisCookie.Name & "<br>" ) Response.Write( "Expires: " & objThisCookie.Expires & "<br>" ) Response.Write( "Secure:" & objThisCookie.Secure & "<br>" ) Array2 = objThisCookie.Values for Loop2 = 0 To Array2.Count - 1 Response.Write( "Value " & Convert.ToString(Loop2) + ": " & Array2.Item(Loop2) &
Note This code is part of the page that you can find at 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.
|