- 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.
TIP
Store information that you are willing to lose in cookies. Users can delete cookies at any time, and some users disable them altogether.
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.
Listing 3.2 WriteCookies.aspx: Writing Arbitrary Cookies
1: <%@ language="C#" %> 2: <script runat="server"> 3: void WriteClicked(Object Sender, EventArgs e) 4: { 5: //Create a new cookie, passing the name into the constructor 6: HttpCookie cookie = 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: DateTime dtNow = DateTime.Now; 13: TimeSpan tsMinute = new TimeSpan(0, 0, 1, 0); 14: cookie.Expires = dtNow + tsMinute; 15: 16: //Add the cookie 17: Response.Cookies.Add(cookie); 18: 19: Response.Write("Cookie written. <br><hr>"); 20: } 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 ReadCoookies.aspx: Reading Cookies Written from the WriteCookies Example
1: <%@ language="C#" %> 2: <script runat="server"> 3: void ReadClicked(Object Sender, EventArgs e) 4: { 5: //Get the cookie name the user entered 6: String strCookieName = NameField.Text; 7: 8: //Grab the cookie 9: HttpCookie cookie = Request.Cookies[strCookieName]; 10: 11: //Check to make sure the cookie exists 12: if (null == cookie) { 13: Response.Write("Cookie not found. <br><hr>"); 14: } 15: else { 16: //Write the cookie value 17: String strCookieValue = cookie.Value.ToString(); 18: Response.Write("The " + strCookieName + " cookie contains: <b>" 19: + strCookieValue + "</b><br><hr>"); 20: } 21: } 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>
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.
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:
HttpCookie cookie = 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. |