HttpRequest 클래스

정의

웹 요청 도중 ASP.NET이 클라이언트에서 보낸 HTTP 값을 읽을 수 있도록 합니다.

public ref class HttpRequest sealed
public sealed class HttpRequest
type HttpRequest = class
Public NotInheritable Class HttpRequest
상속
HttpRequest

예제

다음 예제에서는 클래스의 HttpRequest 속성을 사용하여 현재 요청에 대한 인스턴스에 Request 액세스합니다 Page .

, 또는 CookiesServerVariables 컬렉션의 데이터에 QueryStringForm액세스하기 위해 간소화된 구문을 사용할 수 있습니다. 를 작성 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 요소가 포함되어 있지 않은지 확인합니다. 자세한 내용은 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 메서드 및 속성은 , HttpContextPageUserControl 클래스의 HttpApplication속성을 통해 Request 노출됩니다.

속성에 대한 QueryString 예제와 QueryString같이 , Form또는 CookiesServerVariables 컬렉션에서 데이터에 액세스하려면 작성Request["key"]할 수 있습니다.

참고

클래스 멤버에 대한 HttpRequest 유니코드 지원에는 IIS 버전 6.0 이상이 필요합니다.

생성자

HttpRequest(String, String, String)

HttpRequest 개체를 초기화합니다.

속성

AcceptTypes

클라이언트에서 지원하는 MIME 허용 형식의 문자열 배열을 가져옵니다.

AnonymousID

사용자의 익명 ID를 가져옵니다(있는 경우).

ApplicationPath

ASP.NET 애플리케이션의 가상 애플리케이션 루트 경로를 서버에서 가져옵니다.

AppRelativeCurrentExecutionFilePath

애플리케이션 루트의 가상 경로를 가져온 후 애플리케이션 루트를 물결표(~)로 표시하여 "~/page.aspx"와 같은 상대 경로로 바꿉니다.

Browser

요청 클라이언트의 브라우저 기능에 대한 정보를 가져오거나 설정합니다.

ClientCertificate

현재 요청의 클라이언트 보안 인증서를 가져옵니다.

ContentEncoding

엔터티 본문의 문자 집합을 가져오거나 설정합니다.

ContentLength

클라이언트에서 보낸 콘텐츠의 길이를 바이트 단위로 지정합니다.

ContentType

들어오는 요청의 MIME 콘텐츠 형식을 가져오거나 설정합니다.

Cookies

클라이언트에서 보낸 쿠키 컬렉션을 가져옵니다.

CurrentExecutionFilePath

현재 요청의 가상 경로를 가져옵니다.

CurrentExecutionFilePathExtension

CurrentExecutionFilePath 속성에 지정된 파일 이름의 확장명을 가져옵니다.

FilePath

현재 요청의 가상 경로를 가져옵니다.

Files

클라이언트에서 업로드한 파일 컬렉션을 multipart MIME 형식으로 가져옵니다.

Filter

현재 입력 스트림을 읽을 때 사용할 필터를 가져오거나 설정합니다.

Form

폼 변수의 컬렉션을 가져옵니다.

Headers

HTTP 헤더의 컬렉션을 가져옵니다.

HttpChannelBinding

현재 ChannelBinding 인스턴스의 HttpWorkerRequest 개체를 가져옵니다.

HttpMethod

클라이언트에서 사용하는 HTTP 데이터 전송 메서드(예: GET, POST 또는 HEAD)를 가져옵니다.

InputStream

들어오는 HTTP 엔터티 본문의 콘텐츠를 가져옵니다.

IsAuthenticated

요청이 인증되었는지 여부를 나타내는 값을 가져옵니다.

IsLocal

요청을 로컬 컴퓨터에서 보냈는지 여부를 나타내는 값을 가져옵니다.

IsSecureConnection

HTTP 연결에서 보안 소켓, 즉 HTTPS를 사용하는지 여부를 나타내는 값을 가져옵니다.

Item[String]

지정한 개체를 QueryString, Form, Cookies또는 ServerVariables 컬렉션에서 가져옵니다.

LogonUserIdentity

현재 사용자의 WindowsIdentity 형식을 가져옵니다.

Params

QueryString, Form, CookiesServerVariables 항목의 조합 컬렉션을 가져옵니다.

Path

현재 요청의 가상 경로를 가져옵니다.

PathInfo

URL 확장이 있는 리소스에 대한 추가 경로 정보를 가져옵니다.

PhysicalApplicationPath

현재 실행 중인 서버 애플리케이션의 루트 디렉터리에 대한 실제 파일 시스템 경로를 가져옵니다.

PhysicalPath

요청된 URL에 해당하는 실제 파일 시스템 경로를 가져옵니다.

QueryString

HTTP 쿼리 문자열 변수의 컬렉션을 가져옵니다.

RawUrl

현재 요청의 원시 URL을 가져옵니다.

ReadEntityBodyMode

요청 엔터티 본문을 읽었는지 여부와 읽은 경우 읽은 방법을 나타내는 값을 가져옵니다.

RequestContext

현재 요청의 RequestContext 인스턴스를 가져옵니다.

RequestType

클라이언트에서 사용하는 HTTP 데이터 전송 메서드(예: GET 또는 POST)를 가져오거나 설정합니다.

ServerVariables

웹 서버 변수의 컬렉션을 가져옵니다.

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

IIS에 HTTP 요청 엔터티 본문의 사본을 제공합니다.

InsertEntityBody(Byte[], Int32, Int32)

IIS에 HTTP 요청 엔터티 본문의 사본 및 요청 엔터티 개체에 대한 정보를 제공합니다.

MapImageCoordinates(String)

들어오는 이미지 필드 폼 매개 변수를 적절한 x 좌표와 y 좌표 값에 매핑합니다.

MapPath(String)

지정된 가상 경로를 실제 경로에 매핑합니다.

MapPath(String, String, Boolean)

지정된 가상 경로를 실제 경로에 매핑합니다.

MapRawImageCoordinates(String)

들어오는 이미지 필드 폼 매개 변수를 적절한 x 좌표와 y 좌표 값에 매핑합니다.

MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
SaveAs(String, Boolean)

HTTP 요청을 디스크에 저장합니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
ValidateInput()

Cookies, FormQueryString 속성을 통해 액세스되는 컬렉션에 대해 유효성 검사가 수행되도록 합니다.

적용 대상