HttpRequest Class
TOC
Collapse the table of content
Expand the table of content

HttpRequest Class

 

Enables ASP.NET to read the HTTP values sent by a client during a Web request.

Namespace:   System.Web
Assembly:  System.Web (in System.Web.dll)

System.Object
  System.Web.HttpRequest

public sealed class HttpRequest

NameDescription
System_CAPS_pubmethodHttpRequest(String, String, String)

This API supports the product infrastructure and is not intended to be used directly from your code. Initializes an HttpRequest object.

NameDescription
System_CAPS_pubpropertyAcceptTypes

Gets a string array of client-supported MIME accept types.

System_CAPS_pubpropertyAnonymousID

Gets the anonymous identifier for the user, if present.

System_CAPS_pubpropertyApplicationPath

Gets the ASP.NET application's virtual application root path on the server.

System_CAPS_pubpropertyAppRelativeCurrentExecutionFilePath

Gets the virtual path of the application root and makes it relative by using the tilde (~) notation for the application root (as in "~/page.aspx").

System_CAPS_pubpropertyBrowser

Gets or sets information about the requesting client's browser capabilities.

System_CAPS_pubpropertyClientCertificate

Gets the current request's client security certificate.

System_CAPS_pubpropertyContentEncoding

Gets or sets the character set of the entity-body.

System_CAPS_pubpropertyContentLength

Specifies the length, in bytes, of content sent by the client.

System_CAPS_pubpropertyContentType

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

System_CAPS_pubpropertyCookies

Gets a collection of cookies sent by the client.

System_CAPS_pubpropertyCurrentExecutionFilePath

Gets the virtual path of the current request.

System_CAPS_pubpropertyCurrentExecutionFilePathExtension

Gets the extension of the file name that is specified in the CurrentExecutionFilePath property.

System_CAPS_pubpropertyFilePath

Gets the virtual path of the current request.

System_CAPS_pubpropertyFiles

Gets the collection of files uploaded by the client, in multipart MIME format.

System_CAPS_pubpropertyFilter

Gets or sets the filter to use when reading the current input stream.

System_CAPS_pubpropertyForm

Gets a collection of form variables.

System_CAPS_pubpropertyHeaders

Gets a collection of HTTP headers.

System_CAPS_pubpropertyHttpChannelBinding

Gets the ChannelBinding object of the current HttpWorkerRequest instance.

System_CAPS_pubpropertyHttpMethod

Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.

System_CAPS_pubpropertyInputStream

Gets the contents of the incoming HTTP entity body.

System_CAPS_pubpropertyIsAuthenticated

Gets a value indicating whether the request has been authenticated.

System_CAPS_pubpropertyIsLocal

Gets a value indicating whether the request is from the local computer.

System_CAPS_pubpropertyIsSecureConnection

Gets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS).

System_CAPS_pubpropertyItem[String]

Gets the specified object from the QueryString, Form, Cookies, or ServerVariables collections.

System_CAPS_pubpropertyLogonUserIdentity

Gets the WindowsIdentity type for the current user.

System_CAPS_pubpropertyParams

Gets a combined collection of QueryString, Form, Cookies, and ServerVariables items.

System_CAPS_pubpropertyPath

Gets the virtual path of the current request.

System_CAPS_pubpropertyPathInfo

Gets the additional path information for a resource with a URL extension.

System_CAPS_pubpropertyPhysicalApplicationPath

Gets the physical file system path of the currently executing server application's root directory.

System_CAPS_pubpropertyPhysicalPath

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

System_CAPS_pubpropertyQueryString

Gets the collection of HTTP query string variables.

System_CAPS_pubpropertyRawUrl

Gets the raw URL of the current request.

System_CAPS_pubpropertyReadEntityBodyMode

Gets a value that indicates whether the request entity body has been read, and if so, how it was read.

System_CAPS_pubpropertyRequestContext

Gets the RequestContext instance of the current request.

System_CAPS_pubpropertyRequestType

Gets or sets the HTTP data transfer method (GET or POST) used by the client.

System_CAPS_pubpropertyServerVariables

Gets a collection of Web server variables.

System_CAPS_pubpropertyTimedOutToken

Gets a CancellationToken object that is tripped when a request times out.

System_CAPS_pubpropertyTlsTokenBindingInfo

Gets the TLS token binding information. The property enables applications to retrieve token information from incoming HTTP requests for enhanced authentication.

System_CAPS_pubpropertyTotalBytes

Gets the number of bytes in the current input stream.

System_CAPS_pubpropertyUnvalidated

Gets the HTTP request values without triggering request validation.

System_CAPS_pubpropertyUrl

Gets information about the URL of the current request.

System_CAPS_pubpropertyUrlReferrer

Gets information about the URL of the client's previous request that linked to the current URL.

System_CAPS_pubpropertyUserAgent

Gets the raw user agent string of the client browser.

System_CAPS_pubpropertyUserHostAddress

Gets the IP host address of the remote client.

System_CAPS_pubpropertyUserHostName

Gets the DNS name of the remote client.

System_CAPS_pubpropertyUserLanguages

Gets a sorted string array of client language preferences.

NameDescription
System_CAPS_pubmethodAbort()

Forcibly terminates the underlying TCP connection, causing any outstanding I/O to fail. You might use this method in response to an attack by a malicious HTTP client.

System_CAPS_pubmethodBinaryRead(Int32)

Performs a binary read of a specified number of bytes from the current input stream.

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethodGetBufferedInputStream()

System_CAPS_pubmethodGetBufferlessInputStream()

Gets a Stream object that can be used to read the incoming HTTP entity body.

System_CAPS_pubmethodGetBufferlessInputStream(Boolean)

Gets a Stream object that can be used to read the incoming HTTP entity body, optionally disabling the request-length limit that is set in the MaxRequestLength property.

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodInsertEntityBody()

Provides IIS with a copy of the HTTP request entity body.

System_CAPS_pubmethodInsertEntityBody(Byte[], Int32, Int32)

Provides IIS with a copy of the HTTP request entity body and with information about the request entity object.

System_CAPS_pubmethodMapImageCoordinates(String)

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

System_CAPS_pubmethodMapPath(String)

Maps the specified virtual path to a physical path.

System_CAPS_pubmethodMapPath(String, String, Boolean)

Maps the specified virtual path to a physical path.

System_CAPS_pubmethodMapRawImageCoordinates(String)

Maps an incoming image field form parameter into appropriate x and y coordinate values.

System_CAPS_pubmethodSaveAs(String, Boolean)

Saves an HTTP request to disk.

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_pubmethodValidateInput()

Causes validation to occur for the collections accessed through the Cookies, Form, and QueryString properties.

The methods and properties of the HttpRequest class are exposed through the Request properties of the HttpApplication, HttpContext, Page, and UserControl classes.

To access data from the QueryString, Form, Cookies, or ServerVariables collections, you can write Request["key"], as shown in the example for the QueryString property.

System_CAPS_noteNote

Unicode support for HttpRequest class members requires IIS version 6.0 or later.

The following examples access the HttpRequest instance for the current request by using the Request property of the Page class.

You can use simplified syntax for accessing data from the QueryString, Form, Cookies, or ServerVariables collections. You can write Request["key"].

The first example shows how to retrieve a query string value when loading a page.

public partial class AddToCart : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string rawId = Request["ProductID"];
        int productId;
        if (!String.IsNullOrEmpty(rawId) && int.TryParse(rawId, out productId))
        {
            using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
            {
                usersShoppingCart.AddToCart(productId);
            }
        }
        else
        {
            throw new Exception("Tried to call AddToCart.aspx without setting a ProductId.");
        }
        Response.Redirect("ShoppingCart.aspx");
    }
}

The next example shows how to check if the request is authenticated and retrieve the raw URL.

public partial class RestrictedPage : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Request.IsAuthenticated)
        {
            var rawUrl = Request.RawUrl;
            Response.Redirect("/Account/Login?ru=" + Server.HtmlEncode(rawUrl));
        }
    }
}

A Visual Studio Web site project with source code is available to accompany this topic: Download.

This example uses the StreamWriter class to write the values of several HttpRequest class properties to a file. For properties that are of type string, the values are HTML encoded as they are written to the file. Properties that represent a collection are looped through, and each key/value pair that they contain is written to the file.

System_CAPS_security Security Note

This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<%@ Page Language="C#" %>
<%@ import Namespace="System.Threading" %>
<%@ import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    /* NOTE: To use this sample, create a c:\temp\CS folder,
    *  add the ASP.NET account (in IIS 5.x <machinename>\ASPNET,
    *  in IIS 6.x NETWORK SERVICE), and give it write permissions
    *  to the folder.*/

    private const string INFO_DIR = @"c:\temp\CS\RequestDetails";
    public static int requestCount;

    private void Page_Load(object sender, System.EventArgs e)
    {

        // Create a variable to use when iterating
        // through the UserLanguages property.
        int langCount;

        int requestNumber = Interlocked.Increment(ref requestCount);

        // Create the file to contain information about the request.
        string strFilePath = INFO_DIR + requestNumber.ToString() + @".txt";


        StreamWriter sw = File.CreateText(strFilePath);

        try
        {
            // Write request information to the file with HTML encoding.
            sw.WriteLine(Server.HtmlEncode(DateTime.Now.ToString()));
            sw.WriteLine(Server.HtmlEncode(Request.CurrentExecutionFilePath));
            sw.WriteLine(Server.HtmlEncode(Request.ApplicationPath));
            sw.WriteLine(Server.HtmlEncode(Request.FilePath));
            sw.WriteLine(Server.HtmlEncode(Request.Path));

            // Iterate through the Form collection and write
            // the values to the file with HTML encoding.
            // String[] formArray = Request.Form.AllKeys;
            foreach (string s in Request.Form)
            {
                sw.WriteLine("Form: " + Server.HtmlEncode(s));
            }

            // Write the PathInfo property value
            // or a string if it is empty.
            if (Request.PathInfo == String.Empty)
            {
                sw.WriteLine("The PathInfo property contains no information.");
            }
            else
            {
                sw.WriteLine(Server.HtmlEncode(Request.PathInfo));
            }

            // Write request information to the file with HTML encoding.
            sw.WriteLine(Server.HtmlEncode(Request.PhysicalApplicationPath));
            sw.WriteLine(Server.HtmlEncode(Request.PhysicalPath));
            sw.WriteLine(Server.HtmlEncode(Request.RawUrl));

            // Write a message to the file dependent upon
            // the value of the TotalBytes property.
            if (Request.TotalBytes > 1000)
            {
                sw.WriteLine("The request is 1KB or greater");
            }
            else
            {
                sw.WriteLine("The request is less than 1KB");
            }

            // Write request information to the file with HTML encoding.
            sw.WriteLine(Server.HtmlEncode(Request.RequestType));
            sw.WriteLine(Server.HtmlEncode(Request.UserHostAddress));
            sw.WriteLine(Server.HtmlEncode(Request.UserHostName));
            sw.WriteLine(Server.HtmlEncode(Request.HttpMethod));

            // Iterate through the UserLanguages collection and
            // write its HTML encoded values to the file.
            for (langCount=0; langCount < Request.UserLanguages.Length; langCount++)
            {
                sw.WriteLine(@"User Language " + langCount +": " + Server.HtmlEncode(Request.UserLanguages[langCount]));
            }
       }

       finally
       {
            // Close the stream to the file.
            sw.Close();
       }

        lblInfoSent.Text = "Information about this request has been sent to a file.";
    }


    private void btnSendInfo_Click(object sender, System.EventArgs e)
    {
        lblInfoSent.Text = "Hello, " + Server.HtmlEncode(txtBoxName.Text) +
          ". You have created a new  request info file.";
    }

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <p>
        </p>
        <p>
            Enter your name here:
            <asp:TextBox id="txtBoxName" runat="server"></asp:TextBox>
        </p>
        <p>
            <asp:Button id="btnSendInfo" onclick="btnSendInfo_Click" runat="server" Text="Click Here"></asp:Button>
        </p>
        <p>
            <asp:Label id="lblInfoSent" runat="server"></asp:Label>
        </p>
    </form>
</body>
</html>

.NET Framework
Available since 1.1

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show:
© 2016 Microsoft