다음을 통해 공유


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

이 예제에서는 클래스를 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 메서드와 속성은 , HttpContextPageUserControl 클래스의 HttpApplication속성을 통해 Request 노출됩니다.

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

메모

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

생성자

Name Description
HttpRequest(String, String, String)

개체를 HttpRequest 초기화합니다.

속성

Name Description
AcceptTypes

클라이언트 지원 MIME 수락 형식의 문자열 배열을 가져옵니다.

AnonymousID

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

ApplicationPath

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

AppRelativeCurrentExecutionFilePath

애플리케이션 루트의 가상 경로를 가져오고 애플리케이션 루트에 대한 타일드(~) 표기법을 사용하여 상대적으로 만듭니다("~/page.aspx"에서와 같이).

Browser

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

ClientCertificate

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

ContentEncoding

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

ContentLength

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

ContentType

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

Cookies

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

CurrentExecutionFilePath

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

CurrentExecutionFilePathExtension

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

FilePath

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

Files

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

Filter

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

Form

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

Headers

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

HttpChannelBinding

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

HttpMethod

클라이언트에서 사용하는 HTTP 데이터 전송 방법(예: GET또는POSTHEAD)을 가져옵니다.

InputStream

들어오는 HTTP 엔터티 본문의 내용을 가져옵니다.

IsAuthenticated

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

IsLocal

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

IsSecureConnection

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

Item[String]

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

LogonUserIdentity

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

Params

, FormCookiesServerVariables 항목의 QueryString결합된 컬렉션을 가져옵니다.

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

클라이언트 언어 기본 설정의 정렬된 문자열 배열을 가져옵니다.

메서드

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

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

InsertEntityBody(Byte[], Int32, Int32)

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

MapImageCoordinates(String)

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

MapPath(String, String, Boolean)

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

MapPath(String)

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

MapRawImageCoordinates(String)

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

MemberwiseClone()

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

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

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

ToString()

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

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

및 속성을 통해 액세스하는 컬렉션에 CookiesFormQueryString 대한 유효성 검사가 발생합니다.

적용 대상