通过


HttpRequest 类

定义

允许 ASP.NET 读取客户端在 Web 请求期间发送的 HTTP 值。

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

示例

以下示例使用Request类的属性访问HttpRequest当前请求的Page实例。

可以使用简化的语法来访问来自QueryStringFormCookiesServerVariables集合的数据。 可以编写 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

此示例使用 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通过RequestHttpContextPageUserControl的属性HttpApplication公开。

若要从 QueryStringFormCookiesServerVariables集合访问数据,可以写入Request["key"]该属性的示例QueryString所示。

注释

对类成员的 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 数据传输方法(例如 GETPOSTHEAD)。

InputStream

获取传入 HTTP 实体正文的内容。

IsAuthenticated

获取一个值,该值指示是否已对请求进行身份验证。

IsLocal

获取一个值,该值指示请求是否来自本地计算机。

IsSecureConnection

获取一个值,该值指示 HTTP 连接是否使用安全套接字(即 HTTPS)。

Item[String]

QueryStringFormCookiesServerVariables集合中获取指定对象。

LogonUserIdentity

WindowsIdentity获取当前用户的类型。

Params

获取组合的QueryString集合、FormCookies项和ServerVariables项。

Path

获取当前请求的虚拟路径。

PathInfo

获取具有 URL 扩展的资源的其他路径信息。

PhysicalApplicationPath

获取当前正在执行的服务器应用程序的根目录的物理文件系统路径。

PhysicalPath

获取对应于所请求 URL 的物理文件系统路径。

QueryString

获取 HTTP 查询字符串变量的集合。

RawUrl

获取当前请求的原始 URL。

ReadEntityBodyMode

获取一个值,该值指示请求实体正文是否已读取,如果是,则读取请求实体正文的方式。

RequestContext

获取 RequestContext 当前请求的实例。

RequestType

获取或设置客户端使用的 HTTP 数据传输方法(GETPOST)。

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)

Stream获取可用于读取传入 HTTP 实体正文的对象,可以选择禁用属性中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()

对通过 /> 和 属性访问的集合进行验证。

适用于