The HttpRequest, HttpResponse, HttpServerUtility, and HttpContext Classes


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 Class

The 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:

  • The Request.Form collection contains all the values sent from the controls in a <form> section of the page when the method attribute of the form is "POST"(the default in ASP.NET).

  • The Request.QueryString collection contains all the values sent from the controls in a <form> section of the page when the method attribute of the form is "GET".

  • The Request.Cookies collection contains the values of all the cookies sent by the client with the request.

  • The Request.ServerVariables collection contains the values of all the HTTP headers sent by the client with the request, plus details about the resource location, the client, and the request type (these are used by ASP.NET to populate the many properties of the Request class).

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 Class

The 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

String GetCollectionContents(NameValueCollection nv) {   StringBuilder sb = new StringBuilder();   // iterate through all the keys in the collection   foreach (String key in nv.AllKeys)   {     // get value of this key for display     sb.Append(key + "='"+ nv[key] + "'<br />");   }   return sb.ToString(); }

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

// display the values in the Request collections lblForm.Text = GetCollectionContents(Request.Form); lblQueryString.Text = GetCollectionContents(Request.QueryString); lblCookies.Text = GetCookiesCollectionContents(Request.Cookies); lblServerVariables.Text = GetCollectionContents(                                          Request.ServerVariables);

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

String GetCookiesCollectionContents(HttpCookieCollection cc) {   StringBuilder sb = new StringBuilder();   // iterate through all the cookies in the collection   foreach (String key in cc.AllKeys)   {     // iterate through all the values (subkeys) in this cookie     foreach (String subkey in cc[key].Values)     {       // get value of this subkey for display       sb.Append(key + "["+ subkey + "] ='"+ cc[key][subkey]                     + "'<br />");     }   }   return sb.ToString(); }

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 Response

The 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

void btnCookie_Click(Object sender, EventArgs e) // handle click on "Add cookie" button {   // see if cookie already exists with this name   if (Request.Cookies.Get(txtCookieName.Text) == null)   {     // not found so add a new cookie     Response.Cookies.Add(new HttpCookie(                       txtCookieName.Text, txtCookieValue.Text));   }   else   {     // get the existing cookie and count existing subkeys     HttpCookie cookie = Request.Cookies[txtCookieName.Text];     Int32 vals = cookie.Values.Count;     // add another subkey with new value     cookie.Values["Value" + vals.ToString()] = txtCookieValue.Text;     // remember to add the cookie to the Request     Response.Cookies.Add(cookie);   } }

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 Class

The 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:

  • Accessing the server's name (Server.MachineName)

  • Reading and setting the execution timeout (Server.ScriptTimeout)

  • Translating virtual to physical paths (Server.MapPath)

  • Getting information about the most recent error (Server.GetLastError)

  • Encoding and decoding functions for HTML-and URL-encoded strings, including decoding just the path, and for URL tokens, the to/from byte arrays.

  • Executing another page or transferring execution to another page. You will see these topics discussed in the next Chapter 10.

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

// declare two strings to encode and decode String sSomeHTML   = "This is some'<TEST TEXT>' to encode & decode"; String sSomeURL   = "http://somesite.com/test page.aspx?text=1+2&value=3"; String sEncodedHTML = Server.HtmlEncode(sSomeHTML); String sEncodedURL = Server.UrlEncode(sSomeURL); StringBuilder sb = new StringBuilder(); // display actual strings HTMLEncode the first one for display sb.Append("HTML String is:'<b>"+ sEncodedHTML + "'</b><br />"); sb.Append("URL String is:'<b>"+ sSomeURL + "'</b><p />"); // display encoded and decoded values sb.Append("Server.HtmlEncode(HTML String) is:"   + "<xmp style='font-size:small'>"+ Server.HtmlEncode(sSomeHTML)   + "</xmp>"); sb.Append("Server.HtmlDecode(HTML String) is:"   + "<xmp style='font-size:small'>"+ Server.HtmlDecode(sEncodedHTML)   + "</xmp>"); sb.Append("Server.UrlEncode(URL String) is:"   + "<xmp style='font-size:small'>"+ Server.UrlEncode(sSomeURL)   + "</xmp>"); sb.Append("Server.UrlDecode(URL String) is:"   + "<xmp style='font-size:small'>"+ Server.UrlDecode(sEncodedURL)   + "</xmp>"); sb.Append("Server.UrlPathEncode(URL String) is:"   + "<xmp style='font-size:small'>"+ Server.UrlPathEncode(sSomeURL)   + "</xmp>"); lblResult.Text = sb.ToString();

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 class


However, 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 Class

The 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.




ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net