HttpRequest 类

定义

使 ASP.NET 能够读取客户端在 Web 请求期间发送的 HTTP 值。Enables ASP.NET to read the HTTP values sent by a client during a Web request.

public ref class HttpRequest sealed
public sealed class HttpRequest
type HttpRequest = class
Public NotInheritable Class HttpRequest
继承
HttpRequest

示例

下面的示例HttpRequest Request使用Page类的属性访问当前请求的实例。The following examples access the HttpRequest instance for the current request by using the Request property of the Page class.

您可以使用简化的语法来QueryString访问、 FormCookiesServerVariables集合中的数据。You can use simplified syntax for accessing data from the QueryString, Form, Cookies, or ServerVariables collections. 可以写入Request["key"]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");  
    }  
}  
Public Class AddToCart  
    Inherits Page  
  
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load  
        Dim rawId = Request("ProductID")  
        Dim productId As Integer  
        If Not String.IsNullOrEmpty(rawId) And Integer.TryParse(rawId, productId) Then  
            Using usersShoppingCart As New ShoppingCartActions()  
                usersShoppingCart.AddToCart(productId)  
            End Using  
  
        Else  
            Throw New Exception("Tried to call AddToCart.aspx without setting a ProductId.")  
        End If  
        Response.Redirect("ShoppingCart.aspx")  
    End Sub  
End Class  

下一个示例演示如何检查请求是否经过身份验证并检索原始 URL。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));  
        }  
    }  
}  
Public Class RestrictedPage  
    Inherits Page  
  
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load  
        If Not Request.IsAuthenticated Then  
            Dim rawUrl = Request.RawUrl  
            Response.Redirect("/Account/Login?ru=" + Server.HtmlEncode(rawUrl))  
        End If  
    End Sub  
End Class  

本主题提供了包含源代码的 Visual Studio 网站项目:下载A Visual Studio Web site project with source code is available to accompany this topic: Download.

此示例使用StreamWriter类将多个HttpRequest类属性的值写入文件。This example uses the StreamWriter class to write the values of several HttpRequest class properties to a file. 对于类型为字符串的属性,这些值将在写入文件时以 HTML 编码形式进行编码。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.

重要

此示例具有一个接受用户输入的文本框,这是一个潜在的安全威胁。This example has a text box that accepts user input, which is a potential security threat. 默认情况下,ASP.NET 网页验证用户输入是否不包含脚本或 HTML 元素。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
        {
// <snippet2>
            // 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));
// </snippet2>

// <snippet3>
            // 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));
            }
// </snippet3>

// <snippet4>
            // 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));
            }
// </snippet4>

// <snippet5>
            // 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));
// </snippet5>

// <snippet6>
            // 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");
            }
// </snippet6>

// <snippet7>
            // 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));
// </snippet7>

// <snippet8>
            // 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]));
            }
// </snippet8>
       }

       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>
<%@ Page Language="VB" %>
<%@ 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 INFO_DIR As String = "c:\temp\VB\RequestDetails"
    Public Shared requestCount As Integer

    Private Sub Page_Load(sender As Object, e As System.EventArgs)

        ' Create a variable to use when iterating
        ' through the UserLanguages property.
        Dim langCount As Integer

        ' Create a counter to name the file.
        Dim requestNumber As Integer = _
          Interlocked.Increment(requestCount)

        ' Create the file to contain information about the request.
        Dim strFilePath As String = INFO_DIR & requestNumber.ToString() & ".txt"
        Dim sw As StreamWriter = File.CreateText(strFilePath)

        Try

' <snippet2>
            ' 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))
' </snippet2>

' <snippet3>
            ' Iterate through the Form collection and write
            ' the values to the file with HTML encoding.
            For Each s As String In Request.Form
                sw.WriteLine("Form: " & Server.HtmlEncode(s))
            Next s
' </snippet3>

' <snippet4>
            ' Write the PathInfo property value
            ' or a string if it is empty.
            If Request.PathInfo = String.Empty Then
                sw.WriteLine("The PathInfo property contains no information.")
            Else
                sw.WriteLine(Server.HtmlEncode(Request.PathInfo))
            End If
' </snippet4>

' <snippet5>
            ' 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))
' </snippet5>

' <snippet6>
            ' Write a message to the file dependent upon
            ' the value of the TotalBytes property.
            If Request.TotalBytes > 1000 Then
                sw.WriteLine("The request is 1KB or greater")
            Else
                sw.WriteLine("The request is less than 1KB")
            End If
' </snippet6>

' <snippet7>
            ' 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))
' </snippet7>

' <snippet8>
            ' Iterate through the UserLanguages collection and
            ' write its HTML encoded values to the file.
            For langCount = 0 To Request.UserLanguages.Length - 1
                sw.WriteLine("User Language " & langCount.ToString() & _
                 ": " & Server.HtmlEncode( _
                     Request.UserLanguages(langCount)))
            Next
' </snippet8>

        Finally
            ' Close the stream to the file.
            sw.Close()
        End Try

        lblInfoSent.Text = _
         "Information about this request has been sent to a file."
    End Sub 'Page_Load



    Private Sub btnSendInfo_Click(sender As Object, e As System.EventArgs)
        lblInfoSent.Text = _
         "Hello, " & Server.HtmlEncode(txtBoxName.Text) & _
          ". You have created a new  request info file."
    End Sub 'btnSendInfo_Click

</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>

注解

HttpRequest类的方法和属性Request通过HttpApplicationHttpContextPage和类的属性公开。UserControlThe methods and properties of the HttpRequest class are exposed through the Request properties of the HttpApplication, HttpContext, Page, and UserControl classes.

QueryString若要访问、 FormCookies Request["key"]ServerVariables集合中的数据,可以编写,如QueryString属性的示例中所示。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.

备注

类成员的HttpRequest Unicode 支持需要 IIS 版本6.0 或更高版本。Unicode support for HttpRequest class members requires IIS version 6.0 or later.

构造函数

HttpRequest(String, String, String)

初始化 HttpRequest 对象。Initializes an HttpRequest object.

属性

AcceptTypes

获取客户端支持的 MIME 接受类型的字符串数组。Gets a string array of client-supported MIME accept types.

AnonymousID

获取该用户的匿名标识符(如果存在)。Gets the anonymous identifier for the user, if present.

ApplicationPath

获取服务器上 ASP.NET 应用程序的虚拟应用程序根路径。Gets the ASP.NET application's virtual application root path on the server.

AppRelativeCurrentExecutionFilePath

获取应用程序根目录的虚拟路径,并通过对应用程序根目录使用波形符 (~) 表示法(例如,以“~/page.aspx”的形式)使该路径成为相对路径。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").

Browser

获取或设置有关正在请求的客户端的浏览器功能的信息。Gets or sets information about the requesting client's browser capabilities.

ClientCertificate

获取当前请求的客户端安全证书。Gets the current request's client security certificate.

ContentEncoding

获取或设置实体主体的字符集。Gets or sets the character set of the entity-body.

ContentLength

指定客户端发送的内容长度(以字节计)。Specifies the length, in bytes, of content sent by the client.

ContentType

获取或设置传入请求的 MIME 内容类型。Gets or sets the MIME content type of the incoming request.

Cookies

获取客户端发送的 cookie 的集合。Gets a collection of cookies sent by the client.

CurrentExecutionFilePath

获取当前请求的虚拟路径。Gets the virtual path of the current request.

CurrentExecutionFilePathExtension

获取 CurrentExecutionFilePath 属性中指定的文件名的扩展名。Gets the extension of the file name that is specified in the CurrentExecutionFilePath property.

FilePath

获取当前请求的虚拟路径。Gets the virtual path of the current request.

Files

获取采用多部分 MIME 格式的由客户端上载的文件的集合。Gets the collection of files uploaded by the client, in multipart MIME format.

Filter

获取或设置在读取当前输入流时要使用的筛选器。Gets or sets the filter to use when reading the current input stream.

Form

获取窗体变量集合。Gets a collection of form variables.

Headers

获取 HTTP 头集合。Gets a collection of HTTP headers.

HttpChannelBinding

获取当前 ChannelBinding 实例的 HttpWorkerRequest 对象。Gets the ChannelBinding object of the current HttpWorkerRequest instance.

HttpMethod

获取客户端使用的 HTTP 数据传输方法(如 GETPOSTHEAD)。Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.

InputStream

获取传入的 HTTP 实体主体的内容。Gets the contents of the incoming HTTP entity body.

IsAuthenticated

获取一个值,该值指示是否验证了请求。Gets a value indicating whether the request has been authenticated.

IsLocal

获取一个值,该值指示该请求是否来自本地计算机。Gets a value indicating whether the request is from the local computer.

IsSecureConnection

获取一个值,指示 HTTP 连接是否使用安全套接字(即 HTTPS)。Gets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS).

Item[String]

QueryStringFormCookiesServerVariables 集合获取指定的对象。Gets the specified object from the QueryString, Form, Cookies, or ServerVariables collections.

LogonUserIdentity

获取当前用户的 WindowsIdentity 类型。Gets the WindowsIdentity type for the current user.

Params

获取 QueryStringFormCookiesServerVariables 项的组合集合。Gets a combined collection of QueryString, Form, Cookies, and ServerVariables items.

Path

获取当前请求的虚拟路径。Gets the virtual path of the current request.

PathInfo

获取具有 URL 扩展名的资源的附加路径信息。Gets the additional path information for a resource with a URL extension.

PhysicalApplicationPath

获取当前正在执行的服务器应用程序的根目录的物理文件系统路径。Gets the physical file system path of the currently executing server application's root directory.

PhysicalPath

获取与请求的 URL 相对应的物理文件系统路径。Gets the physical file system path corresponding to the requested URL.

QueryString

获取 HTTP 查询字符串变量集合。Gets the collection of HTTP query string variables.

RawUrl

获取当前请求的原始 URL。Gets the raw URL of the current request.

ReadEntityBodyMode

获取指示请求实体是否被读以及如何被读的值。Gets a value that indicates whether the request entity body has been read, and if so, how it was read.

RequestContext

获取当前请求的 RequestContext 实例。Gets the RequestContext instance of the current request.

RequestType

获取或设置客户端使用的 HTTP 数据传输方法(GETPOST)。Gets or sets the HTTP data transfer method (GET or POST) used by the client.

ServerVariables

获取 Web 服务器变量的集合。Gets a collection of Web server variables.

TimedOutToken

获取请求超时时去除的 CancellationToken 对象。Gets a CancellationToken object that is tripped when a request times out.

TlsTokenBindingInfo

获取 TLS 标记绑定信息。Gets the TLS token binding information. 此属性使应用程序可以从传入的增强身份验证的 HTTP 请求检索令牌信息。The property enables applications to retrieve token information from incoming HTTP requests for enhanced authentication.

TotalBytes

获取当前输入流中的字节数。Gets the number of bytes in the current input stream.

Unvalidated

获取 HTTP 请求值,不触发请求验证。Gets the HTTP request values without triggering request validation.

Url

获取有关当前请求的 URL 的信息。Gets information about the URL of the current request.

UrlReferrer

获取有关客户端上次请求的 URL 的信息,该请求链接到当前的 URL。Gets information about the URL of the client's previous request that linked to the current URL.

UserAgent

获取所提供的客户端浏览器的原始用户代理字符串。Gets the raw user agent string of the client browser that has been provided. 请注意此字符串可能为 Null。Please note it may be null.

UserHostAddress

获取远程客户端的 IP 主机地址。Gets the IP host address of the remote client.

UserHostName

获取远程客户端的 DNS 名称。Gets the DNS name of the remote client.

UserLanguages

获取客户端语言首选项的排序字符串数组。Gets a sorted string array of client language preferences.

方法

Abort()

强制地终止基础 TCP 连接,会导致任何显著的 I/O 失败。Forcibly terminates the underlying TCP connection, causing any outstanding I/O to fail. 可使用此方法来响应恶意 HTTP 客户端的攻击。You might use this method in response to an attack by a malicious HTTP client.

BinaryRead(Int32)

执行对当前输入流进行指定字节数的二进制读取。Performs a binary read of a specified number of bytes from the current input stream.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetBufferedInputStream()

获取一个 Stream 对象,该对象可用于读取传入的 HTTP 实体主体。Gets a Stream object that can be used to read the incoming HTTP entity body.

GetBufferlessInputStream()

获取一个 Stream 对象,该对象可用于读取传入的 HTTP 实体主体。Gets a Stream object that can be used to read the incoming HTTP entity body.

GetBufferlessInputStream(Boolean)

获取能被用于读取正在到来的 HTTP 实体正文的 Stream 对象,同时随意地禁止设置在 MaxRequestLength 属性中的请求长度限制。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.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InsertEntityBody()

向 IIS 提供 HTTP 请求实体正文的副本。Provides IIS with a copy of the HTTP request entity body.

InsertEntityBody(Byte[], Int32, Int32)

向 IIS 提供 HTTP 请求实体正文的副本以及有关请求实体对象的信息。Provides IIS with a copy of the HTTP request entity body and with information about the request entity object.

MapImageCoordinates(String)

将传入图像字段窗体参数映射为适当的 x 坐标值和 y 坐标值。Maps an incoming image-field form parameter to appropriate x-coordinate and y-coordinate values.

MapPath(String)

将指定的虚拟路径映射到物理路径。Maps the specified virtual path to a physical path.

MapPath(String, String, Boolean)

将指定的虚拟路径映射到物理路径。Maps the specified virtual path to a physical path.

MapRawImageCoordinates(String)

将传入图像字段窗体参数映射为适当的 x 和 y 坐标值。Maps an incoming image field form parameter into appropriate x and y coordinate values.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
SaveAs(String, Boolean)

将 HTTP 请求保存到磁盘。Saves an HTTP request to disk.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)
ValidateInput()

对通过 CookiesFormQueryString 属性访问的集合进行验证。Causes validation to occur for the collections accessed through the Cookies, Form, and QueryString properties.

适用于