HttpRequest クラス

定義

Web 要求中にクライアントから送信された HTTP 値を ASP.NET で読み取ることができるようにします。

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

次の例では、 クラスの プロパティをHttpRequest使用して、現在の要求の インスタンスにRequestPageアクセスします。

、または ServerVariables コレクションからCookiesQueryStringFormデータにアクセスするために、簡略化された構文を使用できます。 を記述 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 Web サイト プロジェクトは、「 ダウンロード」のトピックに付属しています。

この例では、 クラスを StreamWriter 使用して、複数 HttpRequest のクラス プロパティの値をファイルに書き込みます。 string 型のプロパティの場合、値はファイルに書き込まれると HTML エンコードされます。 コレクションを表すプロパティはループ処理され、コレクションに含まれる各キーと値のペアがファイルに書き込まれます。

重要

この例には、ユーザー入力を受け付けるテキスト ボックスがあります。これにより、セキュリティが脆弱になる可能性があります。 既定では、ASP.NET Web ページによって、ユーザー入力にスクリプトまたは 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メソッドとプロパティは、および UserControl クラスのプロパティをHttpApplicationHttpContextPage介してRequest公開されます。

、または ServerVariables コレクションからデータにFormQueryStringCookiesアクセスするには、 プロパティの例QueryStringに示すように、 を記述Request["key"]します。

注意

クラス メンバーの HttpRequest Unicode サポートには、IIS バージョン 6.0 以降が必要です。

コンストラクター

HttpRequest(String, String, String)

HttpRequest オブジェクトを初期化します。

プロパティ

AcceptTypes

クライアントにサポートされている MIME で使用できる型の文字列配列を取得します。

AnonymousID

存在する場合は、ユーザーの匿名 ID を取得します。

ApplicationPath

サーバーの ASP.NET アプリケーションの仮想アプリケーション ルート パスを取得します。

AppRelativeCurrentExecutionFilePath

アプリケーション ルートの仮想パスを取得し、ティルダ (~) 表記 ("~/page.aspx" など) を使用した、アプリケーション ルートの相対パスにします。

Browser

要求を実行中のクライアントのブラウザーの性能に関する情報を取得または設定します。

ClientCertificate

現在、要求しているクライアントのセキュリティ証明書を取得します。

ContentEncoding

エンティティ本体の文字セットを取得または設定します。

ContentLength

クライアントから送信されたコンテンツの長さをバイト単位で指定します。

ContentType

受信要求で使用する MIME の Content-Type を取得または設定します。

Cookies

クライアントから送信されたクッキーのコレクションを取得します。

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]

QueryStringFormCookies、または ServerVariables の各コレクションから指定したオブジェクトを取得します。

LogonUserIdentity

現在のユーザーに対する WindowsIdentity の種類を取得します。

Params

QueryStringFormCookies、および ServerVariables の各項目が組み合わされたコレクションを取得します。

Path

現在の要求の仮想パスを取得します。

PathInfo

URL 拡張子付きリソースの追加パス情報を取得します。

PhysicalApplicationPath

現在実行しているサーバー アプリケーションのルート ディレクトリの物理ファイル システム パスを取得します。

PhysicalPath

要求された URL に一致する物理ファイル システム パスを取得します。

QueryString

HTTP クエリ文字列変数のコレクションを取得します。

RawUrl

現在の要求の生の URL を取得します。

ReadEntityBodyMode

要求エンティティ本体が読み取られたかどうかおよび読み取った方法 (読み取られた場合) を示す値を取得します。

RequestContext

現在の要求の RequestContext インスタンスを取得します。

RequestType

クライアントによって使用される HTTP データ転送メソッド (GET または POST) を取得または設定します。

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

受信 HTTP エンティティ本体を読み取るために使用できる Stream オブジェクトを取得します。

GetBufferlessInputStream()

受信 HTTP エンティティ本体を読み取るために使用できる Stream オブジェクトを取得します。

GetBufferlessInputStream(Boolean)

受信 HTTP エンティティ本体を読み取るために使用できる Stream オブジェクトを取得し、オプションで 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()

CookiesForm、および QueryString の各プロパティを通じてアクセスするコレクションに対して検証を実行します。

適用対象