- Day 3: Using Web Forms
- Performing Basic State Management in Web Applications
- Using Cookies
- Using Hidden Fields and Query Strings
- Working with the Session Object
- Working with the Application Object
- Setting Up Global Objects with the global.asax File
- Configuring the Application
- Summary
- Q&A
- Workshop
Using Cookies
Cookies allow you to store small bits of data on the user's computer. They take up a small amount of space on the user's hard drive and are often useful for storing nonessential information, such as user preferences.
ASP.NET lets you manipulate cookies quite easily with the Cookies collection on the Request and Response objects. Listings 3.2 and 3.3 are two companion pages that will read and write cookies that you enter. Figures 3.3 and 3.4 show the two pages.
Figure 3.3 The WriteCookies.aspx page writes cookies to the user's browser.
Figure 3.4 The ReadCookies.aspx page reads cookies stored on a user's browser.
Listing 3.2 WriteCookies.aspx: Writing Arbitrary Cookies
1: <%@ language="VB" %> 2: <script runat="server"> 3: Sub WriteClicked(Sender As Object, e As EventArgs) 4: 5: `Create a new cookie, passing the name into the constructor 6: Dim cookie as HttpCookie = new HttpCookie(NameField.Text) 7: 8: `Set the cookies value 9: cookie.Value = ValueField.Text 10: 11: `Set the cookie to expire in 1 minute 12: Dim dtNow as DateTime = DateTime.Now 13: Dim tsMinute as New TimeSpan(0, 0, 1, 0) 14: cookie.Expires = dtNow.Add(tsMinute) 15: 16: `Add the cookie 17: Response.Cookies.Add(cookie) 18: Response.Write("Cookie written. <br><hr>") 19: 20: End Sub 21: </script> 22: <html> 23: <body> 24: <h3>Use the button below to write cookies to your browser </h3> 25: The cookies will expire in one minute. 26: <form runat="server"> 27: Cookie Name <asp:textbox id="NameField" runat="server"/><br> 28: Cookie Value <asp:textbox id="ValueField" runat="server"/><br> 29: <asp:button text="WriteCookie" onclick="WriteClicked" runat="server" /><br> 30: </form> 31: <a href="readcookies.aspx">Read the cookies</a> 32: </body> 33: </html>
Listing 3.3 ReadCookies.aspx: Reading Cookies Written from the WriteCookies Example
1: <%@ language="VB" %> 2: <script runat="server"> 3: Sub ReadClicked(Sender As Object, e As EventArgs) 4: 5: `Get the cookie name the user entered 6: Dim strCookieName as string = NameField.Text 7: 8: `Grab the cookie 9: Dim cookie as HttpCookie = Request.Cookies(strCookieName) 10: 11: `Check to make sure the cookie exists 12: if cookie Is Nothing then 13: Response.Write("Cookie not found. <br><hr>") 14: else 15: `Write the cookie value 16: Dim strCookieValue as string = cookie.Value.ToString() 17: Response.Write("The " & strCookieName & " cookie contains: <b>" _ 18: & strCookieValue & "</b><br><hr>") 19: end if 20: 21: End Sub 22: </script> 23: <html> 24: <body> 25: Use the button below to read a cookie<br> 26: <form runat="server"> 27: Cookie Name <asp:textbox id="NameField" runat="server" /> 28: <asp:button text="ReadCookie" onclick="ReadClicked" runat="server" /> 29: </form> 30: <a href="writecookies.aspx">Write Cookies</a> 31: </body> 32: </html>
ANALYSIS To write a cookie, create a new HttpCookie object (Line 6 of Listing 3.2), assign a string to its Value property (Line 9), and then call the Add() method on the Response.Cookies object (Line 17). You can also set the time of expiration for a cookie by setting the Expires property to a DateTime value (Line 14).
ReadCookies.aspx in Listing 3.3 shows that it's equally easy to read cookies back, using the Request.Cookies collection (Line 9), which is indexed by cookie name.
Cookies can store only strings, so if you need to store a more complex data type, it must be converted into a string. One possibility for storing complicated data structures is to write the structure out as an XML string and convert it back when reading the cookie.
You can store multiple strings in a cookie by treating each cookie as a collection object. For example, the following would work fine:
Dim cookie As HttpCookie = new HttpCookie("UserFavorites") cookie("FavoriteColor") = "blue" cookie("FavoriteFlavor") = "chocolate"; cookie("FavoriteDrink") = "coffee";
The HttpCookie class contains some advanced properties, listed in Table 3.1.
Table 3.1 Advanced Properties of the HttpCookie Class
Property |
Description |
---|---|
Domain |
Gets/sets the domain name that this cookie belongs to. If set, it restricts access to this cookie from Web servers in the specified domain, such as mycompany.com. |
Path |
Gets/sets the path that this cookie belongs to. If set, it restricts access to this cookie from Web pages in the specified path. |
Secure |
Gets/sets a flag that tells whether the cookie should be transmitted securely to the client browser using the HTTPS protocol. You must have HTTPS set up on your Web server for this option to work. |
HasKeys |
Tells whether the cookie is made up of a collection of strings. |