In most Web programming environments, you access all of the data about a user's request to your Web site, or the response you send back, on the server using the HTTP Request and Response objects. In ASP.NET, these are available (as you saw in the previous chapter) through the HttpRequest and HttpResponse classes. These two classes are accessible through properties of the HttpContext class, andsince the current context is always available in an ASP.NET pageyou can access them simply by using the property names Request and Response: sClientsIPAddress = Request.UserHostAddress; Response.ContentType = "image/png"; Using the HttpRequest ClassThe HttpRequest class provides a series of properties that allow you to access things like the URL and path of the resource requested, the public IP address of the requesting client, the user logon details if the site requires authentication, and the physical location of the resource on your server. It also provides the following four collections, each of the specialized type NameValueCollection, that contain values sent along with the request:
You can even query for a value across all the collections using just Request["value-key"], rather than specifying a particular collectionsuch as Request.Form["value-key"]. The example for the HttpResponse class that you will see shortly demonstrates some of the ways you can use the HttpRequest object to get information about a user's request.
A full list of the properties, methods, and events for the HttpRequest class, which implements the ASP.NET Request object, is at http://msdn2.microsoft.com/library/ha0633cx(en-us,vs.80).aspx. Using the HttpResponse ClassThe HttpResponse class provides a series of properties that are useful if you want to directly manipulate the response sent back to the client. The many properties and methods available include those that manipulate the HTTP headers of the response, manage buffering and caching, set the status values, and provide access to the response stream so that you can inject custom content such as the contents of a disk file. Like the Request object, the Response object also exposes a Cookies collection that contains the values of all the cookies sent to the client for storage on its machine.
A full list of the properties, methods, and events for the HttpResponse class, which implements the ASP.NET Response object, is at http://msdn2.microsoft.com/library/wfa24xy1(en-us,vs.80).aspx. The example here demonstrates some of the ways you can use the HttpRequest and HttpResponse objects to get information about the request and manipulate the response sent to the client. The main body of the page shows the values of some of the Request properties and the contents of the Request collections. To read the Form, QueryString, and ServerVariables collections, the example uses a simple routine, shown in Listing 9.1, to iterate through the AllKeys array of the collection passed to it. For each key in the collection, it extracts the value using the indexer nv[key], and adds it to a StringBuilder. After processing all the keys and values, it returns the contents of the StringBuilder. Listing 9.1. Reading the Contents of a Generic Request Collection
The Page_Load event handler calls this routine three times, with the appropriate Request collection specified and the results inserted into Label controls on the page (see Listing 9.2). Listing 9.2. Populating the Page with the Contents of the Request Collections
However, notice that the Cookies collection requires a different routine, named GetCookiesCollectionContents, in order to display all the values correctly. Listing 9.3 shows this routine. In the case of the Cookies collection, each value is an HttpCookie instance, which implements a range of properties such as the Path, Expiry, and Secure properties. More importantly, each cookie can contain more than one valueeach named HttpCookie instance within the Cookies collection has a Values property that returns a NameValue Collection containing the subkey names and values for this cookie. Listing 9.3. Displaying the Values in the Cookies Collection
Therefore, as you can see in Listing 9.3, the code has to iterate through both the AllKeys array of the collection itself, and then through the Values collection for each cookie. If you are sure that a cookie only contains one value, however, you can just query the Value property of that cookie. Figure 9.1 shows the example page, and you can see the contents of the Request properties and collections. The screenshot shows the results after adding a multivalue cookie to the responseyou can see the values of the form controls in Request.Form collectionand the value of the query string used to load this example is visible in the Request.QueryString collection. The Request.Cookies collection shows the values in the cookie named TestCookie, and you will see how to add cookies to the response shortly. Figure 9.1. The contents of the Request properties and collections
At the bottom of the page are a few values extracted from the Response object, showing things like the character set, encoding, and expiry details of the response (see Figure 9.2). Figure 9.2. Some of the Response properties shown at the bottom of the example page
Adding Cookies to the ResponseThe example page shown in Figure 9.1 demonstrates how you can easily create and add cookies to the response sent to the client. When you click the Add cookie button at the top of the page, an event handler named btnCookie_Click executes. Listing 9.4 shows this routine. It starts by checking if a cookie with the specified name is already present in the Cookies collection, using the Get method of the HttpCookieCollection class. If it does not exist, the Add method adds a new cookie to the collection and automatically makes it part of the response for this page. If the cookie already exists, the code gets a reference to it as an Http-Cookie instance and checks how many values it already has (the number of items in the Values collection). Then it adds a new value to this collection by incrementing the name and then setting the value from the text box on the page. The important point to remember, then, is to add the cookie to the Response, because it is not automatically added in this case. Listing 9.4. Adding or Modifying a Cookie in the Response
When you use the example page, bear in mind that you have to cause the page to post back again after adding a new cookie before it appears in the Request.Cookies collection. Adding the cookie causes it to be stored on the client's machine, and it is only when the next request occurs that the browser sends the new cookie to the server. Using the HttpServerUtility ClassThe HttpServerUtility class provides features that you can use in your code to interact with the current request and response. These features are specific to the low-level actions often required when handling URLs and managing the execution cycle. They include the following:
A full list of the properties, methods, and events for the HttpServer-Utility class, which implements the ASP.NET Server object, is at http://msdn2.microsoft.com/library/z45t6hhk(en-us,vs.80).aspx. This example demonstrates some of the ways you can use the HttpServer-Utility object to work with requests and responses. It declares two String values; the first is a string that includes characters not valid in HTML, and the second is a fictional URL containing characters that are not valid in a URL (see Listing 9.5). Then the code creates an encoded version of each one using the appropriate method (HtmlEncode and UrlEncode). Listing 9.5. Working with the HttpServerUtility Class
Now a StringBuilder creates a String to display in a Label control on the page. First, the code displays the existing values of the two stringsalthough in order for the HTML string to display in the page, the code has to use the HtmlEncoded version. If it does not, the angle brackets would not be visible. Next, a series of <xmp> elements hold the results of applying the various methods of the HttpServerUtility class to the two strings. Figure 9.3 shows the result. You can see that the HtmlEncode method encodes the angle brackets and the ampersand in the HTML string. For the URL string, the UrlEncode method replaces the slashes, spaces, and all other delimiters with the encoded equivalents. This allows the complete URLstring to be passed to another page within (as a parameter of) the URL of the target page without error. Figure 9.3. Using the encoding and decoding methods of the HttpServerUtility classHowever, often you will only want to encode the URL to remove any characters that are not valid when using this string as the URL to load another page, without encoding all the characters. In this case, the UrlPathEncode method gives the required result. Using the HttpContext ClassThe HttpContext class exposes all of the HTTP data about the current request and response. This includes references to the current HttpRequest, HttpResponse, and HttpServerUtility instances (accessed through the Context.Request, Content.Response, and Context.Server properties). It also provides access to the current traceContext for writing trace messages, the HttpSessionState and HttpApplicationState objects to read and set session-level and application-level values, and access for reading configuration and error details. In an ASP.NET page, you do not have to specify this object when you access its properties or methods. For example, you can write to the current traceContext using just: Trace.Write("Warnings", "MyTraceValue"); Inside a component or assembly class, however, you must get a reference to the current context before you can interact with the HTTP request or response. This simply involves querying the Current property of the HttpContext: sClientsIPAddress = HttpContext.Current.Request.UserHostAddress;
A full list of the properties, methods, and events for the HttpContext class, which implements the ASP.NET Context object, is at http://msdn2.microsoft.com/library/b99k0b4w(en-us,vs.80).aspx. |