HttpRequest 類別

定義

允許 ASP.NET 在 Web 要求期間讀取用戶端送出的 HTTP 值。

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

範例

下列範例會使用 Request 類別的 Page 屬性來存取 HttpRequest 目前要求的 實例。

您可以使用簡化的語法,從 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

具有原始程式碼的 Visual Studio 網站專案隨附于本主題: 下載

這個範例會使用 類別, StreamWriter 將數 HttpRequest 個類別屬性的值寫入檔案。 如果是字串類型的屬性,這些值會以 HTML 編碼,因為它們會寫入檔案。 代表集合的屬性會迴圈執行,而且其包含的每個索引鍵/值組都會寫入檔案。

重要

這個範例有一個可接受使用者輸入的文字方塊,這可能會造成安全性威脅。 根據預設,ASP.NET Web 網頁會驗證使用者輸入未包含指令碼或 HTML 項目。 如需詳細資訊,請參閱 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 會透過 RequestHttpContextPageUserControl 類別的屬性 HttpApplication 來公開。

若要從 、、 或 ServerVariables 集合存取資料,您可以寫入 Request["key"] ,如 屬性的範例 QueryStringCookies 所示。 FormQueryString

注意

類別成員的 HttpRequest Unicode 支援需要 IIS 6.0 版或更新版本。

建構函式

HttpRequest(String, String, String)

HttpRequest 物件初始化。

屬性

AcceptTypes

取得用戶端支援的 MIME 接受 (Accept) 類型的字串陣列。

AnonymousID

取得使用者的匿名識別項 (如果有)。

ApplicationPath

取得 ASP.NET 應用程式在伺服器上的虛擬應用程式根路徑。

AppRelativeCurrentExecutionFilePath

取得應用程式根目錄的虛擬路徑,並對應用程式根目錄使用波狀符號 (~) 標記法,讓此路徑變成相對路徑 (就像是 "~/page.aspx")。

Browser

取得或設定關於要求的用戶端瀏覽器功能的資訊。

ClientCertificate

取得目前要求的用戶端安全憑證。

ContentEncoding

取得實體 (Entity) 主體的字元集 (Character Set)。

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

取得 QueryStringFormCookiesServerVariables 項目的組合集合。

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()

強制終止造成任何待處理 I/O 失敗的基礎 TCP 連線。 您可以使用此方法,以回應惡意 HTTP 用戶端攻擊。

BinaryRead(Int32)

在目前輸入資料流執行指定位元組數的二進位讀取。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetBufferedInputStream()

取得可用來讀取傳入 HTTP 實體內容的 Stream 物件。

GetBufferlessInputStream()

取得可用來讀取傳入 HTTP 實體內容的 Stream 物件。

GetBufferlessInputStream(Boolean)

取得 Stream 物件,這個物件可用來讀取傳入 HTTP 實體內容,並選擇性地停用 MaxRequestLength 屬性中所設定的要求長度限制。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
InsertEntityBody()

將 HTTP 要求實體本文的複本提供給 IIS。

InsertEntityBody(Byte[], Int32, Int32)

將 HTTP 要求實體本文的複本及該要求實體物件的相關資訊提供給 IIS。

MapImageCoordinates(String)

將收到的影像欄的表單參數對應至適當的 X 座標和 Y 座標值。

MapPath(String)

將指定的虛擬路徑對應至實體路徑。

MapPath(String, String, Boolean)

將指定的虛擬路徑對應至實體路徑。

MapRawImageCoordinates(String)

將收到的影像欄的表單參數對應至適當的 X 和 Y 座標值。

MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
SaveAs(String, Boolean)

將 HTTP 要求儲存至磁碟。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)
ValidateInput()

會對透過 CookiesFormQueryString 屬性存取的集合進行驗證。

適用於