Programming Microsoft ASP.NET 2.0 Core Reference

 

The HttpRequest Object

The HttpRequest object groups all the information contained in the HTTP packet that represents the incoming Web request. The contents of the various HTTP headers, the query string, or the form's input fields, path, and URL information are organized in a series of collections and other ad hoc objects for easy and effective programmatic access. The HttpRequest object is populated as soon as ASP.NET begins working on a Web request, and it's made available through the Request property of HttpContext.

HttpRequest exposes a fair number of properties and is one of the objects that has been more significantly enriched in the transition from ASP to ASP.NET.

Properties of the HttpRequest Class

The class properties can be categorized into three groups based on the type of information they contain: the type of the request, client data, and connection.

Information about the Request

Table 12-12 lists the properties that define the type of request being issued.

Table 12-12: Properties Describing the Request Type

Property

Description

AcceptTypes

Gets an array of strings denoting the list of MIME types supported by the client for the specified request.

AnonymousID

Indicates the ID of the anonymous user, if any. The identity refers to the string generated by the AnonymousIdentification module and has nothing to do with the identify of the IIS anonymous user. Not available in ASP.NET 1.x.

Browser

Gets an HttpBrowserCapabilities object that contains information about the capabilities of the client's browser.

ContentEncoding

Gets or sets an Encoding object that represents the client's character set. If specified, this property overrides the ASP.NET default encoding.

ContentLength

Gets the length in bytes of the content sent by the client.

ContentType

Gets or sets the MIME content type of the incoming request.

CurrentExecutionFilePath

Gets the current virtual path of the request even when the client is redirected to another page via Execute or Transfer. The FilePath property, on the other hand, always returns the path to the originally requested page.

FilePath

Gets the virtual path of the current request. The path doesn't change in cases of server-side page redirection.

HttpMethod

Gets a string that denotes the HTTP method used for the request. Values are GET, POST, or HEAD.

RequestType

Gets or sets a string that denotes the HTTP command used to issue the request. It can be GET or POST.

TotalBytes

Gets the total number of bytes in the input stream. This property differs from ContentLength in that it also includes headers.

UserAgent

Gets a string that identifies the browser. This property gets the raw content of the user agent header.

In ASP.NET 2.0, the anonymous ID is usually transmitted through a cookie (default name is .ASPXANONYMOUS) and serves the purpose of giving an identity to nonauthenticated users, mainly for user profile functions. The anonymous ID is a Guid and is transmitted as clear text.

It doesn't play any relevant role with authentication and security but is merely a way to track nonregistered users as they move around the site. (See Chapter 5 for profiles and Chapter 15 for user authentication.)

Initially, CurrentExecutionFilePath and FilePath share the same content the requested URL. However, in cases of server-side redirects, the value of CurrentExecutionFilePath is automatically updated. You should check CurrentExecutionFilePath for up-to-date information about the target URL.

The HttpBrowserCapabilities object groups in a single place values that identify a fair number of browser capabilities, including support for ActiveX controls, scripting languages, frames, cookies, and more. When the request arrives, the user agent information is used to identify the requesting browser and an instance of the HttpBrowserCapabilities class is created and populated with browser-specific information. The information is in no way dynamically set by the browser, but is retrieved from an offline server-side repository.

Note 

The Browser property also supports mobile scenarios in version 1.1 of the .NET Framework and newer versions. In this case, the actual object returned is of class MobileCapabilities an HttpBrowserCapabilities-derived class. When you obtain the Browser property reference, you should cast it as a MobileCapabilities class if you are interested in the mobile browser capabilities.

Information from the Client

Table 12-13 lists the HttpRequest properties that expose the client data that ASP.NET pages might want to use for server-side processing. The following table includes, for example, cookies, forms, and query string collections.

Table 12-13: Properties Describing the Client Data

Property

Description

ClientCertificate

Gets an HttpClientCertificate object with information on the client's security certificate settings, if any. The certificate object wraps up information such as number, validity, and issuer of the certificate.

Cookies

Gets a collection representing all cookies sent by the client. A cookie is identified by the HttpCookie object.

Files

Gets a collection of client-uploaded files. The property requires the HTTP Content-Type header to be set to multipart/form-data.

Filter

Gets or sets a Stream-based object through which all HTTP input passes when received. The filtered input is anything read via InputStream.

Form

Gets a name-value collection filled with the values of the input fields in the form posted. The collection is populated when the Content-Type header is either application/x-www-form-urlencoded or multipart/form-data.

Headers

Gets a name-value collection filled with all the header values in the request.

InputStream

Gets a Stream object representing the contents of the incoming HTTP content body.

Params

Gets a name-value collection that is a union of four other similar collections: QueryString, Form, ServerVariables, and Cookies.

QueryString

Gets a name-value collection containing all the query string variables sent by the client.

ServerVariables

Gets a name-value collection filled with a collection of Web server defined variables.

UserHostAddress

Gets the Internet Protocol (IP) address of the remote client.

UserHostName

Gets the Domain Name System (DNS) name of the remote client.

UserLanguages

Gets an array of strings denoting the list of the languages accepted by the client for the specified request. The languages are read from the Accept-Language header.

The Params collection combines four different but homogeneous collections QueryString, Form, ServerVariables, and Cookies and replicates the information contained in each of them. The collections are added in the following order: QueryString, Form, Cookies, and finally ServerVariables.

Information about the Connection

Table 12-14 lists the properties that relate to the open connection.

Table 12-14: Properties Describing the Connection

Property

Description

ApplicationPath

Gets the virtual path of the current application.

IsAuthenticated

Indicates whether the user has been authenticated.

IsLocal

Indicates if it is a local request. Not available in ASP.NET 1.x.

IsSecureConnection

Indicates whether the connection is taking place over a Secure Sockets Layer (SSL) using HTTPS.

LogonUserIdentity

Gets an object representing the Windows identity of the current user as logged at the IIS gate. Not available in ASP.NET 1.x.

Path

Gets the virtual path of the current request.

PathInfo

Gets additional path information for the requested resource, if any. The property returns any text that follows the URL.

PhysicalApplicationPath

Gets the file system path of the current application's root directory.

PhysicalPath

Gets the physical file system path corresponding to the requested URL.

RawUrl

Gets the raw URL of the current request.

Url

Gets the Uri object that represents the URL of the current request.

UrlReferrer

Gets the Uri object that represents the URL from which the current request originated.

The Uri class provides an object representation of a Uniform Resource Identifier (URI) a unique name for a resource available on the Internet. The Uri class provides easy access to the parts of the URI as well as properties and methods for checking host, loopback, ports, and DNS.

The server variables set in the ServerVariables collection are decided by the run-time environment that processes the request. The information packed in the collection is for the most part excerpted from the HTTP worker request object; another part contains Web server specific information. The ServerVariables collection is just a friendly name/value model to expose that information.

Methods of the HttpRequest Class

Table 12-15 lists all methods exposed by the HttpRequest class.

Table 12-15: HttpRequest Methods

Method

Description

BinaryRead

Performs a binary read from the current input stream. The method lets you specify the number of bytes to read and returns an array of bytes. The method is provided for compatibility with ASP. ASP.NET applications should read from the stream associated with the InputStream property.

MapImageCoordinates

Maps an incoming image-field form parameter to x/y coordinate values.

MapPath

Maps the specified virtual path to a physical path on the Web server.

SaveAs

Saves the current request to a file disk with or without headers. This method is especially useful for debugging.

ValidateInput

Performs a quick, non-exhaustive check to find potentially dangerous input data in the request.

Saving the Request to Disk

The SaveAs method lets you create a file to store the entire content of the HTTP request. Note that the storage medium can only be a disk file; no stream or writer can be used. Because ASP.NET by default isn't granted write permissions, this method causes an access denied exception unless you take ad hoc measures. Granting the ASP.NET account full control over the file to be created (or over the whole folder) is one of the possible ways to successfully use the SaveAs method. The following listing shows possible content that SaveAs writes to disk:

GET /ProAspNet20/Samples/Ch12/TestFilter.aspx HTTP/1.1 Connection: Keep-Alive Accept: */* Accept-Encoding: gzip, deflate Accept-Language: en-us,it;q=0.5 Authorization: NTLM TlRMTVNTUAADAAAAIAAAA BcKIogUCzg4AAAAP Cookie: .ASPXANONYMOUS=AcW35sC18TwwNDcyYTMxY w2 Host: localhost User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; snprtz|S04739424200867; .NET CLR 1.1.4322; .NET CLR 2.0.50215) UA-CPU: x86

If, instead, the intercepted request is a POST, you'll find posted values at the bottom of the string.

Validating Client Input

A golden rule of Web security claims that all user input is evil and should always be filtered and sanitized before use. Starting with ASP.NET 1.x, Microsoft added an attribute to the @Page directive that automatically blocks postbacks that contain potentially dangerous data. This feature is not the silver bullet of Web input security, but it helps detect possible problems. From a general security perspective, you're better off replacing the automatic input validation with a strong, application-specific validation layer.

The automatic input validation feature ValidateRequest is enabled by default and implemented via a call to the HttpRequest's ValidationInput method. ValidateInput can be called by your code if the validation feature is not enabled. Request validation works by checking all input data against a hard-coded list of potentially dangerous data. The contents of the collections QueryString, Form, and Cookies are checked during request validation.

 

Категории