HttpRequest 类 
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
使 ASP.NET 能够读取客户端在 Web 请求期间发送的 HTTP 值。
public ref class HttpRequest sealedpublic sealed class HttpRequesttype HttpRequest = classPublic NotInheritable Class HttpRequest- 继承
- 
				HttpRequest
示例
以下示例使用 Request 类的 属性访问HttpRequest当前请求的 Page 实例。
可以使用简化的语法从 QueryString、 Form、 Cookies或 ServerVariables 集合访问数据。 可以编写 Request["key"]。
第一个示例演示如何在加载页面时检索查询字符串值。
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。
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 网站项目: 下载。
此示例使用 StreamWriter 类将多个 HttpRequest 类属性的值写入文件。 对于字符串类型的属性,值在写入文件时进行 HTML 编码。 表示集合的属性将循环访问,并且它们包含的每个键/值对都将写入文件。
重要
此示例具有一个接受用户输入的文本框,这是一个潜在的安全威胁。 默认情况下,ASP.NET 网页验证用户输入是否不包含脚本或 HTML 元素。 有关详细信息,请参阅脚本侵入概述。
<%@ 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 、HttpContext、 Page和 UserControl 类的属性HttpApplication公开。
若要访问 、 、 或 ServerVariables 集合中的数据,可以编写 Request["key"],如 属性的示例QueryStringCookies所示。 FormQueryString
注意
对类成员的 HttpRequest Unicode 支持需要 IIS 6.0 或更高版本。
构造函数
| HttpRequest(String, String, String) | 初始化 HttpRequest 对象。 | 
属性
| AcceptTypes | 获取客户端支持的 MIME 接受类型的字符串数组。 | 
| AnonymousID | 获取该用户的匿名标识符(如果存在)。 | 
| ApplicationPath | 获取服务器上 ASP.NET 应用程序的虚拟应用程序根路径。 | 
| AppRelativeCurrentExecutionFilePath | 获取应用程序根目录的虚拟路径,并通过对应用程序根目录使用波形符(~)表示法,将该路径转变为相对路径(如 "~/page.aspx" 的形式)。 | 
| Browser | 获取或设置有关正在请求的客户端的浏览器功能的信息。 | 
| ClientCertificate | 获取当前请求的客户端安全证书。 | 
| ContentEncoding | 获取或设置实体主体的字符集。 | 
| ContentLength | 指定客户端发送的内容的长度(以字节为单位)。 | 
| ContentType | 获取或设置传入请求的 MIME 内容类型。 | 
| Cookies | 获取客户端发送的 cookie 的集合。 | 
| CurrentExecutionFilePath | 获取当前请求的虚拟路径。 | 
| CurrentExecutionFilePathExtension | 获取 CurrentExecutionFilePath 属性中指定的文件名的扩展名。 | 
| FilePath | 获取当前请求的虚拟路径。 | 
| Files | 获取采用多部分 MIME 格式的由客户端上载的文件的集合。 | 
| Filter | 获取或设置在读取当前输入流时要使用的筛选器。 | 
| Form | 获取窗体变量集合。 | 
| Headers | 获取 HTTP 头集合。 | 
| HttpChannelBinding | 获取当前 ChannelBinding 实例的 HttpWorkerRequest 对象。 | 
| HttpMethod | 获取客户端使用的 HTTP 数据传输方法(如  | 
| InputStream | 获取传入的 HTTP 实体主体的内容。 | 
| IsAuthenticated | 获取一个值,该值指示是否验证了请求。 | 
| IsLocal | 获取指示请求是否来自本地计算机的值。 | 
| IsSecureConnection | 获取一个值,指示 HTTP 连接是否使用安全套接字(即 HTTPS)。 | 
| Item[String] | 从 QueryString、Form、Cookies 或 ServerVariables 集合获取指定的对象。 | 
| LogonUserIdentity | 获取当前用户的 WindowsIdentity 类型。 | 
| Params | 获取 QueryString、Form、Cookies 和 ServerVariables 项的组合集合。 | 
| Path | 获取当前请求的虚拟路径。 | 
| PathInfo | 获取具有 URL 扩展名的资源的附加路径信息。 | 
| PhysicalApplicationPath | 获取当前正在执行的服务器应用程序的根目录的物理文件系统路径。 | 
| PhysicalPath | 获取与请求的 URL 相对应的物理文件系统路径。 | 
| QueryString | 获取 HTTP 查询字符串变量集合。 | 
| RawUrl | 获取当前请求的原始 URL。 | 
| ReadEntityBodyMode | 获取指示请求实体是否被读以及如何被读的值。 | 
| RequestContext | 获取当前请求的 RequestContext 实例。 | 
| RequestType | 获取或设置客户端使用的 HTTP 数据传输方法( | 
| ServerVariables | 获取 Web 服务器变量的集合。 | 
| TimedOutToken | 获取请求超时时去除的 CancellationToken 对象。 | 
| TlsTokenBindingInfo | 获取 TLS 标记绑定信息。 此属性使应用程序可以从传入的增强身份验证的 HTTP 请求检索令牌信息。 | 
| TotalBytes | 获取当前输入流中的字节数。 | 
| Unvalidated | 获取 HTTP 请求值,不触发请求验证。 | 
| Url | 获取有关当前请求的 URL 的信息。 | 
| UrlReferrer | 获取有关客户端上次请求的 URL 的信息,该请求链接到当前的 URL。 | 
| UserAgent | 获取所提供的客户端浏览器的原始用户代理字符串。 请注意此字符串可能为 Null。 | 
| UserHostAddress | 获取远程客户端的 IP 主机地址。 | 
| UserHostName | 获取远程客户端的 DNS 名称。 | 
| UserLanguages | 获取客户端语言首选项的排序字符串数组。 | 
方法
| Abort() | 强制地终止基础 TCP 连接,会导致任何显著的 I/O 失败。 可使用此方法来响应恶意 HTTP 客户端的攻击。 | 
| BinaryRead(Int32) | 执行对当前输入流进行指定字节数的二进制读取。 | 
| Equals(Object) | 确定指定对象是否等于当前对象。(继承自 Object) | 
| GetBufferedInputStream() | 获取一个 Stream 对象,该对象可用于读取传入的 HTTP 实体主体。 | 
| GetBufferlessInputStream() | 获取一个 Stream 对象,该对象可用于读取传入的 HTTP 实体主体。 | 
| GetBufferlessInputStream(Boolean) | 获取能被用于读取正在到来的 HTTP 实体主体的 Stream 对象,同时随意地禁止设置在 MaxRequestLength 属性中的请求长度限制。 | 
| GetHashCode() | 作为默认哈希函数。(继承自 Object) | 
| GetType() | 获取当前实例的 Type。(继承自 Object) | 
| InsertEntityBody() | 向 IIS 提供 HTTP 请求实体正文的副本。 | 
| InsertEntityBody(Byte[], Int32, Int32) | 向 IIS 提供 HTTP 请求实体正文的副本以及有关请求实体对象的信息。 | 
| MapImageCoordinates(String) | 将传入图像字段窗体参数映射为适当的 x 坐标值和 y 坐标值。 | 
| MapPath(String, String, Boolean) | 将指定的虚拟路径映射到物理路径。 | 
| MapPath(String) | 将指定的虚拟路径映射到物理路径。 | 
| MapRawImageCoordinates(String) | 将传入图像字段窗体参数映射为适当的 x 和 y 坐标值。 | 
| MemberwiseClone() | 创建当前 Object 的浅表副本。(继承自 Object) | 
| SaveAs(String, Boolean) | 将 HTTP 请求保存到磁盘。 | 
| ToString() | 返回表示当前对象的字符串。(继承自 Object) | 
| ValidateInput() | 引发对通过 Cookies 、Form 和 QueryString 属性访问的集合的验证。 |