ASP.NET Intrinsic Objects
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 waysGET or POST. GET attaches the data with the URL whereas POST embeds the data within the HTTP request body.
NOTE
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 the CurrentExecutionFilePath returns the path to the redirected page.
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. 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 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 abilities 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 or ASCII) 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 site. |
IsSecureConnection |
Indicates whether the client connection is over a secure HTTPS connection. |
Params |
Represents the form, query string, cookies, and server variables collections 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 querystring 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. |
UserAgent |
Represents the browser being used by the client. |
UserHostAddress |
Represents the IP address of the requesting client's machine. |
UserHostName |
Represents the 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 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. |
Step by Step 3.3 displays some of the path-related properties of the HttpRequest object and calls its 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
-
Add a new Web Form to the project. Name the Web Form StepByStep3-3.aspx. Change the pageLayout property of DOCUMENT element to FlowLayout.
-
Add a Label control (lblInfo) to the Web Form.
-
Switch to the code view of the form. Add the following directives at the top of the code-behind file.
Imports System.Text
Imports System.Collections.Specialized
-
Add the following code to the Page_Load() event handler:
Private Sub Page_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim sbInfo As StringBuilder = New StringBuilder() ' Display some of the path related properties ' of the HttpRequest object sbInfo.Append("The Url of the ASPX page: " & _ Request.Url.ToString & "<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>") Dim nvcHeaders As NameValueCollection = _ Request.Headers Dim astrKeys() As String = nvcHeaders.AllKeys ' Iterate through all header keys ' and display their values Dim strKey As String For Each strKey In astrKeys sbInfo.Append(strKey & ": " & _ nvcHeaders(strKey).ToString()) sbInfo.Append("<br>") Next ' Call MapPath() method to find the physical path ' of the StepByStep3-3.aspx file sbInfo.Append( _ "The physical path of StepByStep3-3.aspx: ") sbInfo.Append(Request.MapPath( _ "StepByStep3-3.aspx")) lblInfo.Text = sbInfo.ToString()
End Sub
-
Set StepByStep3-3.aspx as the start page for the project.
-
Run the project. You should see the Web Form displaying the properties for the current request as shown in Figure 3.3.
Figure 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 of the properties of the HttpRequest object such as Form, QueryString, and Headers 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 the methods of the HttpResponse class.
Table 3.4 - Properties of the HttpResponse Class
Property |
Description |
Buffer |
Indicates whether the output to 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 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 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 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 such as text/html or text/xml. |
Cookies |
Represents the cookies collection that is sent by the server to the client. |
Expires |
Indicates the number of minutes until which the page is cached by the client browser. |
ExpiresAbsolute |
Indicates the specific date and time until which 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 being 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 or 302. |
StatusDescription |
Specifies the text representation of the status of the HTTP output sent to the client. For example, OK or Redirect. |
SupressContent |
Indicates whether the content in the page should be suppressed and not sent to the client. |
NOTE
Caching Policy The properties CacheControl, Expires, and ExpiresAbsolute are provided for backward compatibility. You should instead use the HttpCachePolicy object's methods to set 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 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, PDF file to the response stream. |
Clear() |
Clears the entire response stream buffer, including its 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 round trip to the browser. |
RemoveOutputCacheItem() |
Removes all cache items for the path specified. |
Write() |
Writes output to the outgoing response. |
WriteFile() |
Writes file to the outgoing response. |
Step by Step 3.4 shows the use of the 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
-
Add a new Web Form to the project. Name the Web Form StepByStep3-4.aspx. Change the pageLayout property of DOCUMENT element to FlowLayout.
-
Add a text file to the project and add some random data to the file. Name it Summary.txt.
-
Add a LinkButton control (lbtnDownload) to the Web Form with its Text property set to Download Summary.txt.
-
Double-click the lbtnDownload control and add the following code to the Click event handler:
Private Sub lbtnDownload_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles lbtnDownload.Click ' Append a Header to the response to force a ' Download of the 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 the further execution of the page Response.End()
End Sub
-
Set StepByStep3-4.aspx as the start page for the project.
-
Run the project. Click the link button. You should see a File Download dialog box as shown in the Figure 3.4. After the download, open the file to verify that the file has been successfully downloaded.
Figure 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 Server object. 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 of the HttpServerUtility class.
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 to process the request before the timeout error is sent to the client. |
Table 3.7 - Methods of the HttpServerUtility Class
Method |
Description |
ClearError() |
Clears the last exception from the 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. This method is discussed later in the chapter. |
GetLastError() |
Returns the last exception that occurred on the Web server. This method is discussed in Chapter 4. |
HtmlDecode() |
Enables decoding a string that has been previously HTML encoded for sending over HTTP to a browser. |
HtmlEncode() |
Enables HTML encoding a string for sending over HTTP to a browser. |
MapPath() |
Returns the physical path for a specified virtual path for a Web server. |
Transfer() |
Allows the transfer of ASPX page execution from the current page to another ASPX page on the same Web server. This method is discussed later in the chapter. |
UrlDecode() |
Enables decoding a URL string that has been previously HTML encoded for sending over HTTP to a browser. |
UrlEncode() |
Enables encoding a URL string for safe transmission over HTTP. |
UrlPathEncode() |
Enables encoding of a path portion of the URL string for safe transmission over HTTP. |
STEP BY STEP 3.5 - Using the HttpServerUtility Object
-
Add a new Web Form to the project. Name the Web Form StepByStep3-5.aspx. Change the pageLayout property of the DOCUMENT element to FlowLayout.
-
Add the following code to the Page_Load() event handler:
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' 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>"))
End Sub
-
Set StepByStep3-5.aspx as the start page for the project.
-
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. This is because of the use of HtmlEncode() method of the HttpServerUtility class.
Figure 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 over the course of this book.
Guided Practice Exercise 3.1
Several Web sites collect statistics about the browsers, operating systems, and other settings on their users' computers. This data helps the Web site in customizing content to target a large number of users. A common requirement for Web applications is to find out the browser version 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 and version, the 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 to gather 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:
-
Open the project 315C03. Add a new Web Form named GuidedPracticeExercise3-1 to the project. Change the pageLayout property of the DOCUMENT element to FlowLayout.
-
Add a Label control (lblInfo) to the Web Form.
-
Switch to the code view of the form. Add the following Imports directive at the top of the code-behind file.
Imports System.Text
-
Add the following code to the Page_Load() event handler:
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim sbText As StringBuilder = New StringBuilder() ' Get the reference to the ' HttpBrowserCapabilities object Dim browser As HttpBrowserCapabilities = _ 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.ToString & "<br>") sbText.AppendFormat("ECMA Script Version: " & _ browser.EcmaScriptVersion.ToString & "<br>") sbText.AppendFormat("JavaScript Support: " & _ browser.JavaScript & "<br>") sbText.AppendFormat( _ "Microsoft HTML Document " & _ "Object Model Version: " & _ browser.MSDomVersion.ToString & "<br>") sbText.AppendFormat( _ "World Wide Web (W3C) " & _ "XML Document Object Model " & _ "Version: " & _ browser.W3CDomVersion.ToString & "<br>") lblInfo.Text = sbText.ToString() End Sub
-
Set GuidedPracticeExercise3_1.aspx as the start page for the project.
-
Run the project. You should see the Web Form displaying the properties of the browser as shown in Figure 3.6.
Figure 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 Appendix And perform Step by Step 3.3. After doing this review, try this exercise again.
Review Break
Web applications are disconnected in nature. That is, the values of a page's 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 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.