C# - The HttpRequest Class

The HttpRequest class is under System.Web namespace. It contains properties and methods necessary to handle an HTTP request. It contains all information passed by the browser, including all form variables, certificates and header information. It also contains the CGI server variables.

Properties and Methods of the HttpRequest Class

Item Description
Properties
AcceptTypes Contains a list of supported Multipurpose Internet Mail Extensions (MIME) accept types
ApplicationPath Contains the application root path
Browser Contains information about the browser that is performing the request
ClientCertificate Contains the client security certificate for the current request
ContentEncoding Contains the character set of the current request
ContentLength Contains the length of the content sent by the browser for the current request
ContentType Contains the MIME content type for the current request
Cookies Contains the collection of cookies sent by the browser
FilePath Contains the virtual path of the application
Files Contains the names of the files uploaded by the browser
Form Contains the collection of form variables
Headers Contains the collection of HTTP headers
HttpMethod Contains the HTTP data transfer method
IsAuthenticated Contains True if the user has been authenticated
IsSecureConnection Contains True if the current request was made over a secure connection
Params Contains a combines collection of QueryString, Form, ServerVariable, and Cookie collections
Path Contains the virtual path for the current request
PathInfo Contains additional path information
PhysicalApplicationPath Contains the physical disk location of the root directory for the application
PhysicalPath Contains the physical disk location of the requested uniform resource locator (URL)
QueryString Contains a collection of querystring values for the current request
RawUrl Contains the complete, unmodified URL for the current request
RequestType Contains the data transfer method for the current request
ServerVariables Contains a collection of Web server variables
TotalBytes Contains the total number of bytes of the current request
Url Contains information about the URL of the current request
UrlReferer Contains information about the previous request
UserAgent Contains the contents of the user-agent string, as sent by the browser
UserHostAddress Contains the remote Internet Protocol (IP) address of the client
UserHostName Contains the remote host name of the client
UserLanguages Contains a string array of client language preferences
Methods
MapPath() Maps a virtual path to the actual physical path for the current request
SaveAs() Saves the entire HTTP request to disk
HttpRequest.AcceptTypes

Syntax

String[] AcceptTypes

Description

The AcceptTypes property contains an array of all accepted MIME types

Example

int index;
string output;


String[] myArray = Request.AcceptTypes;
for(index = 0; index < myArray.Length; index++){
   output = "Accept Type " + index + ": " + myArray[index] + "<br>";

}
HttpRequest.ApplicationPath

Syntax

String ApplicationPath

Description

The ApplicationPath property contains the virtual path of the application.

Example

string AppPath = Request.ApplicationPath;
HttpRequest.Browser

Syntax

HttpBrowserCapabilities Browser

Description

The Browser object contains information about the capabilities of the browser that is making the request.

Example

HttpBrowserCapabilities BrowCaps = new HttpBrowserCapabilities();
BrowCaps = Request.Browser;
HttpRequest.ClientCertificate

Syntax

HttpClientCertificate ClientCertificate

Description

The ClientCertificate property returns an object containing information about the client's security certificate.

Example

Object clientCertificate = Request.ClientCertificate;
HttpRequest.ContentEncoding

Syntax

Encoding ContentEncoding

Description

The ContentEncoding property contains an object with information about the character set of the client.

Example

String EncodingType;
EncodingType = Request.ContentEncoding.EncodingName;
HttpRequest.ContentLength

Syntax

String ContentLength

Description

The ContentLength property contains the length of the entire client request.

Example

String contentLength = Request.ContentLength;
HttpRequest.ContentType

Syntax

String ContentType;

Description

The ContentType property contains information about the MIME content type of the client making the request.

Example

String contentType = Request.ContentType;
HttpRequest.Cookies

Syntax

HttpCookieCollection Cookies

Description

The Cookies property contains a collection of all the cookies passed by the client in the current request.

Example

HttpCookieCollection cookies = Request.Cookies;
HttpRequest.FilePath

Syntax

String FilePath

Description

The FilePath property contains the virtual path of the current request. The information returned does not contain any querystring information appended to the end of the URL.

Example

string filepath = Request.FilePath;
HttpRequest.Files

Syntax

HttpFileCollection Files

Description

The Files property contains a collection of files uploaded by the client in the current request. This collection is populated only if the client uploads files.

Example

<% @Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<html>
<head>
     <script language="C#" runat="server">
          void Page_Load(Object Source, EventArgs E){
              if(IsPostBack == true){
                  string[] fileArray = new string[Request.Files.Count];
                  fileArray = Request.Files.AllKeys;

                  //For simplicity of presentation, only look at first file
                  fileName.Text = Request.Files.Get(0).FileName;
                  fileSize.Text = Request.Files.Get(0).ContentLength.ToString();
                  fileType.Text = Request.Files.Get(0).ContentType;

                  try{
                       Request.Files.Get(0).SaveAs(txtSaveLocation.Text);
                  }catch(Exception e){ }
              }
          }
     </script>

</head>
<body>
<h1>Uploading Files</h1>
<form enctype="multipart/form-data" runat="server">
    <p>
    File to Upload: <br>
    <input type="file" id="fileupload" runat="server">
    </p>


    <p>
    Location to Save on Server (including file name): <br>
    <asp:TextBox id="txtSaveLocation" runat="server"></asp:TextBox><br>
    <input type="submit">
    </p>
    <p>
    <h2>File Information</h2>
    <b>File Name:</b> <asp:label id="fileName" runat="server"></asp:label><br>
    <b>File Size:</b> <asp:label id="fileSize" runat="server"></asp:label><br>
    <b>File Type:</b> <asp:label id="fileType" runat="server"></asp:label><br>
    </p>
</form>

</body>
</html>
HttpRequest.Form

Syntax

NameValueCollection Form

Description

The Form property is a collection of all form values passed from the client during the submission of a form.

Example

string formValue = Request.Form["txtName"];
HttpRequest.Headers

Syntax

NameValueCollection Headers

Description

The Headers property is a collection of all the headers passed by the client in the request.

Example

string contentLength = Request.Headers["Content-Length"];
HttpRequest.HttpMethod

Syntax

String HttpMethod

Description

The HttpMethod property is used to determine the type of data transfer method used by the form. The three possible values are GET, POST, and HEAD.

Example

string requestMethod = Request.HttpMethod;
HttpRequest.IsAuthenticated

Syntax

Boolean IsAuthenticated

Description

The IsAuthenticated property contains True if the remote user has been authenticated.

Example

Boolean isAuthenticated = Request.IsAuthenticated;
HttpRequest.IsSecureConnection

Syntax

Boolean IsSecureConnection

Description

The IsSecureConnection property contains True if the current request was made over a secure connection (that is, the URL starts with https://).

Example

Boolean IsSecureConnection = Request.IsSecureConnection;
HttpRequest.Params

Syntax

NameValueCollection Params

Description

The Params property contains a combined collection of all querystring, form, cookie, and server variables submitted with the current request.

Example

string output;


for(int i=0; i < Request.Params.Count; i++)
     output += Request.Params[i] + "<br>";
HttpRequest.Path

Syntax

String Path

Description

The Path property contains the virtual path for the current request.

Example

string virtualPath = Request.Path;
HttpRequest.PathInfo

Syntax

String PathInfo

Description

The PathInfo property contains additional path information for the current request. Specifically, the PathInfo property is empty unless the requested URL jas a tail with appended information.

Example

string pathInfo = Request.PathInfo;
HttpRequest.PhysicalApplicationPath

Syntax

String PhysicalApplicationPath

Description

The PhysicalApplicationPath property contains the physical file system directory of the current application.

Example

string appPath = Request.PhysicalApplicationPath;
HttpRequest.PhysicalPath

Syntax

String PhysicalPath

Description

The PhysicalPath property contains the physical file system path of the current request.

Example

string physicalPath = Request.PhysicalPath;
HttpRequest.QueryString

Syntax

NameValueCollection QueryString

Description

The QueryString property is a collection of all querystring items in the current request.

Example

string myName = Request.QueryString["txtName"];
HttpRequest.RawUrl

Syntax

String RawUrl

Description

The RawUrl property contains the entire URL for the current request. If the URL is http://www.triconsole.com/index.php?auth=true, then the RawUrl property is /index.php?auth=true.

Example

string rawUrl = Request.RawUrl;
HttpRequest.RequestType

Syntax

String RequestType

Description

The RequestType property contains the data transfer method for the current request. The value contains GET or POST.

Example

string requestType = Request.RequestType;
HttpRequest.ServerVariables

Syntax

NameValueCollection ServerVariables

Description

The ServerVariables property contains a collection of all the Web server variables for the current request.

Example

string output = "";


for(int i=0; i < Request.ServerVariables.Count; i++)
   output += Request.ServerVariables[i] + "<br>";
HttpRequest.TotalBytes

Syntax

Int32 TotalBytes

Description

The TotalBytes property contains the size of the current request, in bytes.

Example

int totalBytes = Request.TotalBytes;
HttpRequest.Url

Syntax

Uri Url

Description

The Url property returns an object of type Uri (defined in the System namespace).

Example

Uri UrlInfo = Request.Url;
string absolutePath = UrlInfo.AbsolutePath;
HttpRequest.UrlReferrer

Syntax

Uri UrlReferrer

Description

The UrlReferrer property contains information about the referring URL (that is, the page the user was visiting before accessing the current page).

Example

Uri UrlReferrerInfo = Request.Url;
string absolutePath = UrlReferrerInfo.AbsolutePath;
HttpRequest.UserAgent

Syntax

String UserAgent

Description

The UserAgent property contains the entire user-agent header for the browser that is making the request. For the version of Microsoft Internet Explorer that ships with Windows 2000, the user-agent is Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0; COM+ 1.0.2615).

Example

string userAgent = Request.UserAgent;
HttpRequest.UserHostAddress

Syntax

String UserHostAddress

Description

The UserHostAddress property contains the IP Address of the remote client that is making the request.

Example

string remoteAddr = Request.UserHostAddress;
HttpRequest.UserHostName

Syntax

String UserHostName

Description

The UserHostName property contains the remote Domain Name Server (DNS) host name of the client that is performing the current request.

Example

string remoteHost = Request.UserHostName;
HttpRequest.UserLanguages

Syntax

String[] UserLanguages

Description

The UserLanguages property contains a string array of the language preferences of the client.

Example

string output = "";


for(int i=0; i < Request.UserLanguages.Length; i++)
    output = output + Request.UserLanguages[i] + "<br>";
HttpRequest.MapPath()

Syntax

String MapPath(String virtualPath)
String MapPath(String virtualPath, String baseVirtualDir, Boolean allowCrossAppMapping)

Description

The MapPath() method accepts a string containing a virtual path and returns the actual physical application directory for the virtual path.

Example

string rootIisPath = MapPath("/");
HttpRequest.SaveAs()

Syntax

void SaveAs(String filename, Boolean includeHeaders)

Description

The SaveAs() method saves the entire request to disk. The first argument is a string containing a physical disk location. If the second argument is true, then the headers will be saved to disk as well. The SaveAs() method could be used to save a client request to disk in the case of an error so that it could be fully debugged later.

Example

Request.SaveAs("c:\\temp\\entireRequest.txt", true);