ASP.NET 4 Unleased - p 130 docx

10 130 0
ASP.NET 4 Unleased - p 130 docx

Đang tải... (xem toàn văn)

Thông tin tài liệu

ptg 1264 CHAPTER 28 Maintaining Application State Finally, we examine a feature introduced with ASP.NET 2.0 the Profile object. The Profile object provides you with a method of creating a strongly typed and persistent form of session state. You learn different methods of defining a profile. You also learn how to use the Profile object from within a component. Finally, you learn how to implement a custom Profile provider. Using Browser Cookies Cookies were introduced into the world with the first version of the Netscape browser. The developers at Netscape invented cookies to solve a problem that plagued the Internet at the time. There was no way to make money because there was no way to create a shop- ping cart. Here’s how cookies work. When a web server creates a cookie, an additional HTTP header is sent to the browser when a page is served to the browser. The HTTP header looks like this: Set-Cookie: message=Hello This Set-Cookie header causes the browser to create a cookie named message that has the value Hello. After a cookie has been created on a browser, whenever the browser requests a page from the same application in the future, the browser sends a header that looks like this: Cookie: message=Hello The Cookie header contains all the cookies that have been set by the web server. The cookies are sent back to the web server each time a request is made from the browser. A cookie is nothing more than a little bit of text. You can store only string values when using a cookie. You actually can create two types of cookies: session cookies and persistent cookies. A session cookie exists only in memory. If a user closes the web browser, the session cookie disappears forever. A persistent cookie, on the other hand, can last for months or even years. When you create a persistent cookie, the cookie is stored permanently by the user’s browser on the user’s computer. Internet Explorer, for example, stores cookies in a set of text files contained in the following folder: \Documents and Settings\[user]\Cookies From the Library of Wow! eBook ptg 1265 Using Browser Cookies The Mozilla Firefox browser, on the other hand, stores cookies in the following file: \Documents and Settings\[user]\Application Data\Mozilla\Firefox\Profiles\ ➥ [random folder name]\Cookies.txt Because different browsers store cookies in different locations, cookies are browser-relative. If you request a page that creates a cookie when using Internet Explorer, the cookie doesn’t exist when you open Firefox or Opera. Furthermore, both Internet Explorer and Firefox store cookies in clear text. You should never store sensitive information—such as Social Security numbers or credit card numbers in a cookie. NOTE Where does the name cookie come from? According to the original Netscape cookie specification, the term cookie was selected “for no compelling reason.” However, the name most likely derives from the UNIX world in which a “magic cookie” is an opaque token passed between programs. Cookie Security Restrictions Cookies raise security concerns. When you create a persistent cookie, you are modifying a file on a visitor’s computer. There are people who sit around all day dreaming up evil things that they can do to your computer. To prevent cookies from doing horrible things to people’s computers, browsers enforce a number of security restrictions on cookies. First, all cookies are domain-relative. If the Amazon website sets a cookie, the Barnes & Noble website cannot read the cookie. When a browser creates a cookie, the browser records the domain associated with the cookie and doesn’t send the cookie to another domain. NOTE An image contained in a web page might be served from another domain than the web page itself. Therefore, when the browser makes a request for the image, a cookie can be set from the other domain. Companies, such as DoubleClick, that display and track advertisements on multiple websites take advantage of this loophole to track adver- tisement statistics across multiple websites. This type of cookie is called a third-party cookie. 28 From the Library of Wow! eBook ptg 1266 CHAPTER 28 Maintaining Application State The other important restriction that browsers place on cookies is a restriction on size. A single domain cannot store more than 4,096 bytes. This size restriction encompasses the size of both the cookie names and the cookie values. NOTE Internet Explorer supports a feature named the userData behavior, which enables you to persist far more data than a cookie (10,240KB for an intranet site and 1,024 for an Internet site). To learn more about the userData behavior, visit the Microsoft MSDN website (msdn.microsoft.com). Finally, most browsers restrict the number of cookies that can be set by a single domain to no more than 20 cookies (but not Internet Explorer). If you attempt to set more than 20 cookies, the oldest cookies are automatically deleted. Because of all the security concerns related to cookies, all modern browsers provide users with the option of disabling cookies. This means that unless you are building an Intranet application and you control every user’s browser, you should attempt to not rely on cookies. Strive to use cookies only when storing noncrucial information. That said, many parts of ASP.NET Framework rely on cookies. For example, Web Parts, Forms Authentication, Session state, and anonymous Profiles all depend on cookies by default. If you depend on one of these features, there is no reason not to use cookies. Furthermore, many websites rely on cookies. Many sections of the Yahoo! and MSDN websites you cannot visit without having cookies enabled. In other words, requiring visitors to have cookies enabled to use your website is not an entirely unreasonable requirement. Creating Cookies You create a new cookie by adding a cookie to the Response.Cookies collection, which contains all the cookies sent from the web server to the web browser. For example, the page in Listing 28.1 enables you to create a new cookie named Message. The page contains a form that enables you to enter the value of the Message cookie (see Figure 28.1). From the Library of Wow! eBook ptg 1267 Using Browser Cookies FIGURE 28.1 Creating a new cookie. LISTING 28.1 SetCookie.aspx <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <script runat=”server”> protected void btnAdd_Click(object sender, EventArgs e) { Response.Cookies[“message”].Value = txtCookieValue.Text; } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <title>Set Cookie</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:Label id=”lblCookieValue” Text=”Cookie Value:” 28 From the Library of Wow! eBook ptg 1268 CHAPTER 28 Maintaining Application State AssociatedControlID=”txtCookieValue” Runat=”server” /> <asp:TextBox id=”txtCookieValue” Runat=”server” /> <asp:Button id=”btnAdd” Text=”Add Value” OnClick=”btnAdd_Click” Runat=”server” /> </div> </form> </body> </html> Be warned that cookie names are case-sensitive. Setting a cookie named message is differ- ent from setting a cookie named Message. If you want to modify the value of the cookie created by the page in Listing 28.1, you can open the page and enter a new value for the message cookie. When the web server sends its response to the browser, the modified value of the cookie is set on the browser. The page in Listing 28.1 creates a session cookie. The cookie disappears when you close your web browser. If you want to create a persistent cookie, you need to specify an expira- tion date for the cookie. The page in Listing 28.2 creates a persistent cookie. LISTING 28.2 SetPersistentCookie.aspx <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <script runat=”server”> void Page_Load() { // Get current value of cookie int counter = 0; if (Request.Cookies[“counter”] != null) counter = Int32.Parse(Request.Cookies[“counter”].Value); // Increment counter counter++; From the Library of Wow! eBook ptg 1269 Using Browser Cookies // Add persistent cookie to browser Response.Cookies[“counter”].Value = counter.ToString(); Response.Cookies[“counter”].Expires = DateTime.Now.AddYears(2); // Display value of counter cookie lblCounter.Text = counter.ToString(); } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <title>Set Persistent Cookie</title> </head> <body> <form id=”form1” runat=”server”> <div> You have visited this page <asp:Label id=”lblCounter” Runat=”server” /> times! </div> </form> </body> </html> The page in Listing 28.2 tracks the number of times that you request the page. A persistent cookie named counter tracks page requests. The counter cookie’s Expires property is set to 2 years in the future. When you set a particular expiration date for a cookie, the cookie is stored as a persistent cookie. Reading Cookies You use the Response.Cookies collection to create and modify cookies. You use the Request.Cookies collection to retrieve a cookie’s value. For example, the page in Listing 28.3 retrieves the message cookie’s value. 28 From the Library of Wow! eBook ptg 1270 CHAPTER 28 Maintaining Application State LISTING 28.3 GetCookie.aspx <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <script runat=”server”> void Page_Load() { if (Request.Cookies[“message”] != null) lblCookieValue.Text = Request.Cookies[“message”].Value; } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <title>Get Cookie</title> </head> <body> <form id=”form1” runat=”server”> <div> The value of the message cookie is: <asp:Label id=”lblCookieValue” Runat=”server” /> </div> </form> </body> </html> In Listing 28.3, the IsNothing() function checks whether the cookie exists before reading its value. If you don’t include this check, you might get a null reference exception. Also, don’t forget that cookie names are case-sensitive. The page in Listing 28.4 lists all cookies contained in the Request.Cookies collection (see Figure 28.2). From the Library of Wow! eBook ptg 1271 Using Browser Cookies FIGURE 28.2 Displaying a list of all cookies. LISTING 28.4 GetAllCookies.aspx <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <script runat=”server”> void Page_Load() { ArrayList colCookies = new ArrayList(); for (int i = 0; i < Request.Cookies.Count; i++) colCookies.Add(Request.Cookies[i]); grdCookies.DataSource = colCookies; grdCookies.DataBind(); } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <title>Get All Cookies</title> </head> <body> <form id=”form1” runat=”server”> 28 From the Library of Wow! eBook ptg 1272 CHAPTER 28 Maintaining Application State <div> <asp:GridView id=”grdCookies” Runat=”server”/> </div> </form> </body> </html> The only meaningful information that you get back from iterating through the Request.Cookies collection is the HasKeys, Name, and Value properties. The other columns show incorrect information. For example, the Expires column always displays a minimal date. Browsers don’t communicate these additional properties with page requests, so you can’t retrieve these property values. When using the Request.Cookies collection, you need to understand that a For Each loop returns different values than a For Next loop. If you iterate through the Request.Cookies collection with a For Each loop, you get the cookie names. If you iterate through the collection with a For Next loop, you get instances of the HttpCookie class (described in the next section). Setting Cookie Properties Cookies are represented with the HttpCookie class. When you create or read a cookie, you can use any of the properties of this class: . Domain—Enables you to specify the domain associated with the cookie. The default value is the current domain. . Expires—Enables you to create a persistent cookie by specifying an expiration date. . HasKeys—Enables you to determine whether a cookie is a multi-valued cookie (see the section “Working with Multivalued Cookies” later in this chapter). . HttpOnly—Enables you to prevent a cookie from being accessed by JavaScript. . Name—Enables you to specify a name for a cookie. . Path—Enables you to specify the path associated with a cookie. The default value is /. . Secure—Enables you to require a cookie to be transmitted across a Secure Sockets Layer (SSL) connection. . Value—Enables you to get or set a cookie value. . Values—Enables you to get or set a particular value when working with a multival- ued cookie. (See the section “Working with Multivalued Cookies” later in this chapter.) From the Library of Wow! eBook ptg 1273 Using Browser Cookies A couple of these properties require additional explanation. For example, you might find the Domain property confusing because you can’t change the domain associated with a cookie. The Domain property is useful when your organization includes subdomains. If you want to set a cookie that can be read by the Sales.MyCompany.com, Managers.MyCompany.com, and Support.MyCompany.com domains, you can set the Domain property to the value .MyCompany.com. (Notice the leading period.) You can’t, however, use this property to asso- ciate a cookie with an entirely different domain. The HttpOnly property enables you to specify whether a cookie can be accessed from JavaScript code. This property works only with Internet Explorer 6 (Service Pack 1) and above. The property was introduced to help prevent cross-site scripting attacks. The Path property enables you to scope cookies to a particular path. For example, if you host multiple applications in the same domain, and you do not want the applications to share the same cookies, you can use the Path property to prevent one application from reading another application’s cookies. The Path property sounds useful. Unfortunately, you should never use it. Internet Explorer performs a case-sensitive match against the path. If a user uses a different case when typing the path to a page into the address bar, the cookie isn’t sent. In other words, the following two paths don’t match: http://localhost/original/GetAllCookies.aspx http://localhost/ORIGINAL/GetAllCookies.aspx Deleting Cookies The method for deleting cookies is not intuitive. To delete an existing cookie, you must set its expiration date to a date in the past. The page in Listing 28.5 illustrates how you can delete a single cookie. The page contains a form field for the cookie name. When you submit the form, the cookie with the speci- fied name is deleted. LISTING 28.5 DeleteCookie.aspx <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <script runat=”server”> protected void btnDelete_Click(object sender, EventArgs e) { Response.Cookies[txtCookieName.Text].Expires = DateTime.Now.AddDays(-1); } </script> 28 From the Library of Wow! eBook . cross-site scripting attacks. The Path property enables you to scope cookies to a particular path. For example, if you host multiple applications in the same domain, and you do not want the applications. use the Path property to prevent one application from reading another application’s cookies. The Path property sounds useful. Unfortunately, you should never use it. Internet Explorer performs. ptg 12 64 CHAPTER 28 Maintaining Application State Finally, we examine a feature introduced with ASP. NET 2.0 the Profile object. The Profile object provides you with a method

Ngày đăng: 06/07/2014, 18:20

Tài liệu cùng người dùng

Tài liệu liên quan