ASP.NET Intrinsic Objects

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

Table 4.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

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 HttpRequest intrinsic object can be accessed by the Request property of the Page class. Tables 4.2 and 4.3 list the properties and methods of the HttpRequest class, respectively. Note that all the properties except the Filter property of the HttpRequest class are read-only.

Table 4.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 included 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 4.3. Methods of the HttpRequest Class

Method

Description

Method

Description

BinaryRead()

Reads the specified number of bytes from the request stream. This method is provided for backward compatibility; you should use the 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.

The following code segment displays the header information sent by the client to the server:

 // Display the request header System.Collections.Specialized.NameValueCollection       nvcHeaders = Request.Headers; String[] astrKeys = nvcHeaders.AllKeys; // Iterate through all header keys and display their values foreach (String strKey in astrKeys) {     Response.Write(strKey + ": " + nvcHeaders[strKey].ToString());     Response.Write("<br>"); } 

Some properties of the HttpRequest objectsuch as Form , QueryString , Headers , and so onreturn a NameValueCollection containing a collection of key-value pairs of their contents. The previous code segment demonstrates 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 enable you to set its behavior and operations. The Response property of the Page class provides access to the HttpResponse object. Tables 4.4 and 4.5 list the properties and methods of the HttpResponse class, respectively.

Table 4.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 is 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, 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

Returns a TextWriter object that enables writing custom 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.

Table 4.5. Methods of the HttpResponse Class

Method

Description

AddCacheItemDependencies()

Specifies that the current cached response is dependent on the items specified in a given ArrayList object.

AddCacheItemDependency()

Specifies that the current cached response is dependant on the item specified in the given String object.

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.

ApplyAppPathModifier()

In case of a cookieless session, it adds a session ID to the given virtual path.

BinaryWrite()

Allows writing binary data such as an image file or a 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 a file to the outgoing response.

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

  1. Add a new Visual C# ASP.NET Web Application project to the solution, and name it Example4_2 . Change the pageLayout property of the DOCUMENT element of the Web form 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:

     private void lbtnDownload_Click(object sender, System.EventArgs e) {     // Force a download of Summary.txt as an attachment     Response.AppendHeader("Content-Disposition",        "Attachment;FileName=" + "Summary.txt");     // 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(); } 
  5. Run the project. Click the link button; you should see a File Download dialog box that enables you to save the file locally.

The HttpServerUtility Object

The HttpServerUtility object contains utility methods and properties to work with the Web server. It also 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 4.6 and 4.7 list the properties and methods of this class, respectively.

Table 4.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 4.7. Methods of the HttpServerUtility Class

Method

Description

ClearError()

Clears the last exception from memory

CreateObject()

Creates a COM object on the server

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

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 given string for safe transmission over HTTP

UrlPathEncode()

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



MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
ISBN: 789729016
EAN: N/A
Year: 2005
Pages: 191

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