ASP.NET 3.5 : The HTTP Request Context - The HttpRequest Object

9/17/2012 3:34:16 AM
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 1 lists the properties that define the type of request being issued.

Table 1. Properties Describing the Request Type
AcceptTypesGets an array of strings denoting the list of MIME types supported by the client for the specified request.
AnonymousIDIndicates 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.
BrowserGets an HttpBrowserCapabilities object that contains information about the capabilities of the client’s browser.
ContentEncodingGets or sets an Encoding object that represents the client’s character set. If specified, this property overrides the ASP.NET default encoding.
ContentLengthGets the length in bytes of the content sent by the client.
ContentTypeGets or sets the MIME content type of the incoming request.
CurrentExecutionFilePathGets 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.
FilePathGets the virtual path of the current request. The path doesn’t change in cases of server-side page redirection.
HttpMethodGets a string that denotes the HTTP method used for the request. Values are GET, POST, or HEAD.
RequestTypeGets or sets a string that denotes the HTTP command used to issue the request. It can be GET or POST.
TotalBytesGets the total number of bytes in the input stream. This property differs from ContentLength in that it also includes headers.
UserAgentGets a string that identifies the browser. This property gets the raw content of the user agent header.

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; it is merely a way to track nonregistered users as they move around the site. 

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; instead, it is retrieved from an offline server-side repository.


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 2 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 2. Properties Describing the Client Data
ClientCertificateGets 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.
CookiesGets a collection representing all cookies sent by the client. A cookie is identified by the HttpCookie object.
FilesGets a collection of client-uploaded files. The property requires the HTTP Content-Type header to be set to multipart/form-data.
FilterGets or sets a Stream-based object through which all HTTP input passes when received. The filtered input is anything read via InputStream.
FormGets 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.
HeadersGets a name-value collection filled with all the header values in the request.
InputStreamGets a Stream object representing the contents of the incoming HTTP content body.
ParamsGets a name-value collection that is a union of four other similar collections: QueryString, Form, ServerVariables, and Cookies.
QueryStringGets a name-value collection containing all the query string variables sent by the client.
ServerVariablesGets a name-value collection filled with a collection of Web server–defined variables.
UserHostAddressGets the Internet Protocol (IP) address of the remote client.
UserHostNameGets the Domain Name System (DNS) name of the remote client.
UserLanguagesGets 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 it 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 3 lists the properties that relate to the open connection.

Table 3. Properties Describing the Connection
ApplicationPathGets the virtual path of the current application.
IsAuthenticatedIndicates whether or not the user has been authenticated.
IsLocalIndicates if it is a local request. Not available in ASP.NET 1.x.
IsSecureConnectionIndicates whether the connection is taking place over a Secure Sockets Layer (SSL) using HTTPS.
LogonUserIdentityGets an object representing the Windows identity of the current user as logged at the IIS gate. Not available in ASP.NET 1.x.
PathGets the virtual path of the current request.
PathInfoGets additional path information for the requested resource, if any. The property returns any text that follows the URL.
PhysicalApplicationPathGets the file system path of the current application’s root directory.
PhysicalPathGets the physical file system path corresponding to the requested URL.
RawUrlGets the raw URL of the current request.
UrlGets the Uri object that represents the URL of the current request.
UrlReferrerGets 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 4 lists all methods exposed by the HttpRequest class.

Table 4. HttpRequest Methods
BinaryReadPerforms 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.
MapImageCoordinatesMaps an incoming image-field form parameter to x/y coordinate values.
MapPathMaps the specified virtual path to a physical path on the Web server.
SaveAsSaves the current request to a file disk with or without headers. This method is especially useful for debugging.
ValidateInputPerforms a quick, nonexhaustive 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 /Core35/Samples/Ch14/Misc/TestFilter.aspx HTTP/1.1Connection: Keep-Alive
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: it,en-us;q=0.5
Host: localhost:1066
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR
2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.590; .NET CLR 3.0.04506.648; .NET CLR
UA-CPU: x86


If the intercepted request is a POST, instead, 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. The @Page directive has an attribute—ValidateRequest—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.

PS4 game trailer XBox One game trailer
WiiU game trailer 3ds game trailer
Top 10 Video Game
-   Minecraft Mods - MAD PACK #10 'NETHER DOOM!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Minecraft Mods - MAD PACK #9 'KING SLIME!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Minecraft Mods - MAD PACK #2 'LAVA LOBBERS!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Minecraft Mods - MAD PACK #3 'OBSIDIAN LONGSWORD!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Total War: Warhammer [PC] Demigryph Trailer
-   Minecraft | MINIONS MOVIE MOD! (Despicable Me, Minions Movie)
-   Minecraft | Crazy Craft 3.0 - Ep 3! "TITANS ATTACK"
-   Minecraft | Crazy Craft 3.0 - Ep 2! "THIEVING FROM THE CRAZIES"
-   Minecraft | MORPH HIDE AND SEEK - Minions Despicable Me Mod
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 92 "IS JOE DEAD?!"
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 93 "JEDI STRIKE BACK"
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 94 "TATOOINE PLANET DESTRUCTION"
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 95 "TATOOINE CAPTIVES"
-   Hitman [PS4/XOne/PC] Alpha Gameplay Trailer
-   Satellite Reign [PC] Release Date Trailer
Game of War | Kate Upton Commercial