Home > Articles

  • Print
  • + Share This
This chapter is from the book

ASP.NET Intrinsic Objects

Use and edit intrinsic objects. Intrinsic objects include response, request, session, server, and application.

  • Retrieve values from the properties of intrinsic objects.

  • Set values on the properties of intrinsic objects.

  • Use intrinsic objects to perform operations.

ASP.NET provides intrinsic objects to enable low-level access to the Web application framework. With the help of these intrinsic objects, you can work directly with the underlying HTTP streams, server, session, and application objects. The intrinsic objects can be accessed in a Web form through the properties of the Page class. Table 3.1 lists the important intrinsic objects and the properties of the Page class to which they are mapped.

Table 3.1 Intrinsic Objects and Their Mappings to the Page Class Properties

Intrinsic Object

Property of the Page Class

HttpRequest

Request

HttpResponse

Response

HttpServerUtility

Server

HttpApplicationState

Application

HttpSessionState

Session


I'll discuss the HttpRequest, HttpResponse, and HttpServerUtility objects in the following section. The other two objects, HttpApplicationState and HttpSessionState, are discussed later in this chapter in the section "State Management."

The HttpRequest Object

The HttpRequest object . represents the incoming request from the client to the Web server. The request from the client can come in two ways—GET or POST. GET attaches the data with the URL, whereas POST embeds the data within the HTTP request body.

The requested page and its details are encapsulated in an HttpRequest object. The HttpRequest intrinsic object can be accessed by the Request property of the Page class. Tables 3.2 and 3.3 list the properties and methods of the HttpRequest class, respectively. Because the HttpRequest class provides information about the request sent by the client, all the properties are read-only except the Filter property.

Table 3.2 Properties of the HttpRequest Class

Property

Description

AcceptTypes

Specifies the MIME types that the client browser accepts.

ApplicationPath

Represents the application's virtual application root path on the server.

Browser

Provides access to the capabilities and characteristics of the requesting browser.

ClientCertificate

Represents the certificate, if any, sent by the client for secure communications.

ContentEncoding

Represents the character encoding (such as UTF7, ASCII, and so on) for the entity body.

ContentLength

Specifies the length in bytes of the request.

ContentType

Specifies the MIME type of the incoming request.

Cookies

Represents the cookies collection that is sent by the client to the server.

CurrentExecutionFilePath

Specifies the virtual path of the current executing page on the Web server.

FilePath

Specifies the virtual path of the file on the Web server.

Files

Represents the file collection that is posted by the client to the Web server.

Filter

Represents a stream that is applied as a filter on the incoming request.

Form

Specifies the contents of a form posted to the server.

Headers

Represents the HTTP headers passed in with the incoming request.

HttpMethod

Represents the method of the HTTP request (for example, GET, POST, or HEAD).

InputStream

Represents the stream that contains the incoming HTTP request body.

IsAuthenticated

Indicates whether the client has been authenticated to the Web site.

IsSecureConnection

Indicates whether the client connection is over a secure HTTPS connection.

Params

Represents the form, query string, cookies, and server variables collection of the current request.

Path

Specifies the virtual path of the current request, along with additional path information.

PathInfo

Specifies the additional path information of the current request.

PhysicalApplicationPath

Specifies the physical file system path of the application's root directory.

PhysicalPath

Specifies the physical file system path of the current request on the Web server.

QueryString

Represents the query string collection sent by the client to the Web server through the URL.

RawUrl

Specifies the URL portion of the current request, excluding the domain information.

RequestType

Represents the type of request (GET or POST) made by the client.

ServerVariables

Represents the collection of Web server variables.

TotalBytes

Represents the total number of bytes posted to the server in the current request.

Url

Specifies information about the current URL request.

UrlReferrer

Specifies the URL of the client's previous request that linked to the current URL request.

UserAgent

Represents the browser being used by the client.

UserHostAddress

Represents the IP address of the requesting client's machine.

UserHostName

Represents the Domain Name System (DNS) name of the requesting client's machine.

UserLanguages

Specifies the languages preferred by the client's browser.


Table 3.3 Methods of the HttpRequest Class

Method

Description

BinaryRead()

Reads the specified number of bytes from the request stream. This method is provided for backward compatibility; you should use InputStream property instead.

MapImageCoordinates()

Returns the coordinates of a form image that is sent to the server in the current request.

MapPath()

Returns the physical file system path of the file for a specified virtual path of a Web server.

SaveAs()

Saves the current HTTP request into a disk file, with an option to include or exclude headers.


CurrentExecutionFilePath

This property of the HttpRequest class returns the file path of the currently executing page. When using the server-side redirection methods such as Server.Execute() and Server.Transfer(), the FilePath property returns the path to the original page, whereas CurrentExecutionFilePath returns the path to the currently executing page.

Step by Step 3.3 displays some of the path-related properties of the HttpRequest object and calls the MapPath() method to get the physical file system path for a specified virtual path. It also displays the header information sent by the client to the server when the StepByStep3_3.aspx page is requested from the server.

STEP BY STEP

3.3 Using the HttpRequest Intrinsic Object

  1. Add a new Web form to the project. Name the Web form StepByStep3_3.aspx. Change the pageLayout property of the DOCUMENT element to FlowLayout.

  2. Add a Label control (lblInfo) to the Web form.

  3. Switch to the code view of the form. Add the following using directive at the top of the code-behind file:

  4. using System.Text;

  5. Add the following code to the Page_Load() event handler:

  6. private void Page_Load(
      object sender, System.EventArgs e)
    {
      StringBuilder sbInfo = new StringBuilder();
    
      // Display some of the path related properties 
      // of the HttpRequest object
      sbInfo.Append("The Url of the ASPX page: " + 
        Request.Url + "<br>");
      sbInfo.Append("The Virtual File Path: " + 
        Request.FilePath + "<br>");
      sbInfo.Append("The Physical File Path: " + 
        Request.PhysicalPath + "<br>");
      sbInfo.Append("The Application Path: " + 
        Request.ApplicationPath + "<br>");
      sbInfo.Append("The Physical Application Path: " +
        Request.PhysicalApplicationPath + "<br>");
    
      // Display the request header
      sbInfo.Append("Request Header:");
      sbInfo.Append("<br>");
      NameValueCollection nvcHeaders = Request.Headers;
      String[] astrKeys = nvcHeaders.AllKeys;
      // Iterate through all header keys 
      // and display their values
      foreach (String strKey in astrKeys)
      {
        sbInfo.Append(strKey + ": " + 
          nvcHeaders[strKey].ToString());
        sbInfo.Append("<br>");
      }
      // Call MapPath() method to find the physical path
      // of StepByStep3_2.aspx
      sbInfo.Append(
        "The physical path of StepByStep3_2.aspx: ");
      sbInfo.Append(
        Request.MapPath("StepByStep3_2.aspx"));
      lblInfo.Text = sbInfo.ToString();
    }
  7. Set StepByStep3_3.aspx as the start page in the project.

  8. Run the project. You should see the Web form displaying the properties for the current request, as shown in Figure 3.3.

Figure 3.3Figure 3.3 The Request property of the Page class returns an HttpRequest object that gives access to the HTTP values sent by a client during a Web request.

Some properties of the HttpRequest object—such as Form, QueryString, Headers, and so on—return a NameValueCollection containing a collection of key-value pairs of their contents. Step by Step 3.3 shows how to iterate through this collection by iterating through the keys of the Headers collection and displaying the key and value of each header sent by the client.

The HttpResponse Object

The HttpResponse object represents the response sent back to the client from the Web server. It contains properties and methods that provide direct access to the response stream and allow you to set its behavior and operations. The Response property of the Page class provides access to the HttpResponse object. Tables 3.4 and 3.5 list the properties and methods of the HttpResponse class, respectively.

Table 3.4 Properties of the HttpResponse Class

Property

Description

Buffer

Indicates whether output to the response stream needs to be buffered and sent to the client after the entire page is processed. This property is provided for backward compatibility; the BufferOutput property should be used instead.

BufferOutput

Indicates whether the output to the response stream needs to be buffered and then sent to the client after the entire page is processed. The default is true.

Cache

Represents the caching policy of the page. The policy controls where caching can be done, the expiration time, and so on.

CacheControl

Specifies where the caching should be done. The possible values are Public and Private.

Charset

Represents the character set of the output stream. If set to null, the content-type header will be suppressed.

ContentEncoding

Represents the character set of the response output stream.

ContentType

Represents the MIME type for the outgoing response stream like text/html, text/xml, and so on.

Cookies

Represents the cookies collection that is sent by the server to the client.

Expires

Indicates the number of minutes until the page is cached by the client browser.

ExpiresAbsolute

Indicates the specific date and time until the page is cached by the client browser.

Filter

Represents a stream that is applied as a filter to the outgoing response.

IsClientConnected

Indicates whether the client is connected to the server. This property is very helpful when running a lengthy request.

Output

Allows writing text output to the outgoing response.

OutputStream

Allows writing binary output to the outgoing response.

Status

Specifies the status of the HTTP output that is sent to the client. This property returns both the status code and the text description of the status (for example, 200 OK).

StatusCode

Specifies the numeric representation of the status of the HTTP output sent to the client (for example, 200, 302, and so on).

StatusDescription

Specifies the text representation of the status of the HTTP output sent to the client. (for example, OK, Redirect, and so on).

SupressContent

Indicates whether the content in the page should be suppressed and not sent to the client.


Caching Policy

The properties CacheControl, Expires, and ExpiresAbsolute are provided for backward compatibility. You should instead use the HttpCachePolicy object's methods to set the caching policy. This object is returned by the Cache property. Setting caching policy is discussed in Chapter 15, "Configuring a Web Application."

Table 3.5 Methods of the HttpResponse Class

Method

Description

AddCacheItemDependencies()

Makes the validity of the cache item dependent on the other items in the cache.

AddCacheItemDependency()

Makes the validity of the cache item dependent on another item in the cache.

AddFileDependencies()

Adds a group of files to the collection on which the current response depends.

AddFileDependency()

Adds a file to the collection on which the current response depends.

AddHeader()

Adds an HTTP header to the outgoing response stream. This method is provided for backward compatibility with ASP.

AppendHeader()

Adds an HTTP header to the outgoing response stream.

AppendToLog()

Adds information to the IIS Web log file.

BinaryWrite()

Allows writing binary data such as an image file or PDF file to the response stream.

Clear()

Clears the entire response stream buffer, including ts contents and headers.

ClearContent()

Clears the entire content portion of the response stream buffer.

ClearHeaders()

Clears the headers portion of the response stream buffer.

Close()

Closes the response object and the socket connection to the client.

End()

Stops the execution of the page after flushing the output buffer to the client.

Flush()

Flushes the currently buffered content out to the client.

Pics()

Adds a PICS-label HTTP header to the outgoing response.

Redirect()

Redirects the client browser to any URL. This method requires an additional roundtrip to the browser.

RemoveOutputCacheItem()

Removes all cache items for the path specified.

Write()

Writes output to the outgoing response.

WriteFile()

Writes a file to the outgoing response.


Step by Step 3.4 shows the use of HttpResponse object methods and properties to create a response that displays the File Download dialog box and allows the user to download a text file from the Web server to the client's machine.

STEP BY STEP

3.4 Using the HttpResponse Intrinsic Object

  1. Add a new Web form to the project. Name the Web form StepByStep3_4.aspx. Change the pageLayout property of the DOCUMENT element to FlowLayout.

  2. Add a text file to the project that contains some data that needs to be downloaded. Name it Summary.txt.

  3. Add a LinkButton control (lbtnDownload) to the Web form with its Text property set to Download Summary.txt.

  4. Double-click the lbtnDownload control and add the following code to the Click event handler:

  5. private void lbtnDownload_Click(object sender, 
      System.EventArgs e)
    {
      // Append a Header to the response to force a
      // Download of Summary.txt as an attachment
      Response.AppendHeader("Content-Disposition", 
        "Attachment;FileName=" + "Summary.txt");
    
      // Set the Content type to text/plain 
      // As the download file is a TXT file
      Response.ContentType = "text/plain";
    
      // Write the file to the Response
      Response.WriteFile("Summary.txt");
    
      // Stop further execution of the page
      Response.End();
    }
  6. Set StepByStep3_4.aspx as the start page in the project.

  7. Run the project. Click the link button. You should see a File Download dialog box, as shown in Figure 3.4. After the download, open the file to verify that the file has been successfully downloaded.

Figure 3.4Figure 3.4 The File Download dialog box provides the interface to download a file from the Web server.

The HttpServerUtility Object

The HttpServerUtility object contains utility methods and properties to work with the Web server. It contains methods to enable HTML/URL encoding and decoding, execute or transfer to an ASPX page, create COM components, and so on. The Server property of the Page class provides access to the HttpServerUtility object. Tables 3.6 and 3.7 list the properties and methods of the HttpServerUtility class, respectively.

Table 3.6 Properties of the HttpServerUtility Class

Property

Description

MachineName

Returns the name of the server that hosts the Web application.

ScriptTimeout

Indicates the number of seconds that are allowed to elapse when processing the request before a timeout error is sent to the client.


Table 3.7 Methods of the HttpServerUtility Class

Method

Description

ClearError()

Clears the last exception from memory. This method is discussed in Chapter 4, "Error Handling for the User Interface."

CreateObject()

Creates a COM object on the server. This method is discussed in Chapter 10, "Working with Legacy Code."

CreateObjectFromClsid()

Creates a COM object on the server identified by a specified class identifier (CLSID).

Execute()

Executes an ASPX page within the current requested page.

GetLastError()

Returns the last exception that occurred on the Web server. This method is discussed in Chapter 4.

HtmlDecode()

Decodes a string that has been previously encoded to eliminate invalid HTML characters.

HtmlEncode()

Encodes a string converting any characters that are illegal in HTML for transmission over HTTP.

MapPath()

Returns the physical path for a specified virtual path on a Web server.

Transfer()

Allows the transfer of ASPX page execution from the current page to another ASPX page on the same Web server.

UrlDecode()

Decodes a string that has been previously encoded to eliminate invalid characters for transmission over HTTP in a URL.

UrlEncode()

Encodes a string converting any characters that are illegal in URL for HTTP transmission.

UrlPathEncode()

Encodes the path portion of the URL string for safe transmission over HTTP.


STEP BY STEP

3.5 Using the HttpServerUtility Intrinsic Object

  1. Add a new Web form to the project. Name the Web form StepByStep3_5.aspx. Change the pageLayout property of DOCUMENT element to FlowLayout.

  2. Add the following code to the Page_Load() event handler:

  3. private void Page_Load(
      object sender, System.EventArgs e)
    {
      // Write to the response
      // using the Server.HtmlEncode() method
      // so that the browser does not parse
      // the text into HTML elements
      Response.Write(Server.HtmlEncode(
        "To include a title in the title bar, " + 
        "enclose your chosen title between the " + 
        "pairs of the <title>...</title> element " + 
        "in the HTML <head> element. "));
    
      Response.Write(Server.HtmlEncode(
        "For example, <title> " + 
        "Using the HtmlEncode() method </title>."));
    }
  4. Set StepByStep3_5.aspx as the Start page in the project.

  5. Run the project. You should see that the browser does not parse the HTML <title> elements written to the response, as shown in Figure 3.5, because of the use of the HtmlEncode() method of the HttpServerUtility class.

Figure 3.5Figure 3.5 The HtmlEncode() method of the HttpServerUtility object. HTML encodes a string to be displayed in the browser.

I will discuss various other methods of the HttpServerUtility object throughout the course of this book.

Guided Practice Exercise 3.1

Several Web sites collect statistics about the browsers, operating system, and other settings on their users' computers. This data helps the Web sites customize their contents to target a large number of users. A common requirement for Web applications is to find out the browser versions of their users and then serve them files that are optimized for that particular browser version.

In this exercise, you are required to create a Web form that displays the following information about the client browser: the browser name, version, platform of the client's computer, the CLR version installed, JavaScript support, ECMA version, MS DOM version, and the W3C XML DOM version supported by the browser.

You can use the Request.Browser property to get access to the HttpBrowserCapabilities object that provides various properties that contain information on the capabilities of the client's browser.

How would you create a Web form that allows the Web page to get information about the browser?

You should try working through this problem on your own first. If you are stuck, or if you'd like to see one possible solution, follow these steps:

  1. Open the project 315C03. Add a new Web form GuidedPracticeExercise3_1.aspx to the project. Change the pageLayout property of DOCUMENT element to FlowLayout.

  2. Add a Label control (lblInfo) to the Web form.

  3. Switch to the code view of the form. Add the following using directive at the top of the code-behind file:

  4. using System.Text;
  5. Add the following code to the Page_Load() event handler:

  6. private void Page_Load(
      object sender, System.EventArgs e)
    {
      StringBuilder sbText = new StringBuilder();
    
      // Get the reference to the 
      // HttpBrowserCapabilities object 
      HttpBrowserCapabilities browser = Request.Browser;
    
      // Display the properties of the 
      // HttpBrowserCapabilities Class
      sbText.AppendFormat("Browser : " + 
        browser.Browser + "<br>");
      sbText.AppendFormat("Browser Version: " + 
        browser.Version + "<br>");
      sbText.AppendFormat("Client's Platform: " + 
        browser.Platform + "<br>");
      sbText.AppendFormat(".NET CLR Version: " + 
        browser.ClrVersion + "<br>");
      sbText.AppendFormat("ECMA Script Version: " + 
        browser.EcmaScriptVersion + "<br>");
      sbText.AppendFormat("JavaScript Support: " + 
        browser.JavaScript + "<br>");
      sbText.AppendFormat(
       "Microsoft HTML Document Object Model Version: "
        + browser.MSDomVersion + "<br>");
      sbText.AppendFormat(
        "World Wide Web (W3C) XML Document " + 
        " Object Model Version: " + 
        browser.W3CDomVersion + "<br>");
    
      lblInfo.Text=sbText.ToString();
    }
  7. Set GuidedPracticeExercise3_1.aspx as the start page in the project.

  8. Run the project. You should see the Web form displaying the properties of the browser as shown in Figure 3.6.

Figure 3.6Figure 3.6 The HttpBrowserCapabilities object provides access to the capabilities of the client's browser.

If you have difficulty following this exercise, review the section "The HttpRequest Object" earlier in this chapter and perform Step by Step 3.3. Also, look at the .NET Framework documentation for the System.Web.HttpBrowserCapabilities class. After doing this review, try this exercise again.

REVIEW BREAK

  • Web applications are disconnected in nature. Values of page variables and controls are not preserved across the page requests.

  • You can use the Page.IsPostBack property to determine whether a page is being loaded for the first time or in response to a postback operation.

  • ASP.NET has a feature called smart navigation that can greatly enhance the user experience of a Web page for the users of Internet Explorer 5.0 or higher browsers.

  • ASP.NET provides intrinsic objects to enable low-level access to the Web application framework. With the help of these intrinsic objects, you can work directly with the underlying HTTP request, HTTP response, server, session, and application objects.

  • + Share This
  • 🔖 Save To Your Account