HttpRequest Sınıf

Tanım

ASP.NET bir Web isteği sırasında istemci tarafından gönderilen HTTP değerlerini okumasını sağlar.

public ref class HttpRequest sealed
public sealed class HttpRequest
type HttpRequest = class
Public NotInheritable Class HttpRequest
Devralma
HttpRequest

Örnekler

Aşağıdaki örnekler, sınıfının özelliğini kullanarak geçerli isteğin örneğine Request erişmektedir.HttpRequest Page

, , FormCookiesveya ServerVariables koleksiyonlarından verilere erişmek için basitleştirilmiş söz dizimini QueryStringkullanabilirsiniz. yazabilirsiniz Request["key"].

İlk örnekte, bir sayfa yüklenirken sorgu dizesi değerinin nasıl alınacakları gösterilmektedir.

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

Sonraki örnekte isteğin kimliğinin doğrulanıp doğrulanmamış olup olmadığını denetleme ve ham URL'yi alma işlemi gösterilmektedir.

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

Kaynak kodu içeren bir Visual Studio Web sitesi projesi şu konuya eşlik edebilir: İndir.

Bu örnek, bir dosyaya birkaç HttpRequest sınıf özelliğinin değerlerini yazmak için sınıfını kullanırStreamWriter. Dize türünde özellikler için, değerler dosyaya yazıldıkları gibi HTML kodlanmışlardır. Bir koleksiyonu temsil eden özellikler döngüye geçirilir ve içerdikleri her anahtar/değer çifti dosyaya yazılır.

Önemli

Bu örnekte, olası bir güvenlik tehdidi olan kullanıcı girişini kabul eden bir metin kutusu vardır. Varsayılan olarak, ASP.NET Web sayfaları kullanıcı girişinin betik veya HTML öğeleri içermediğini doğrular. Daha fazla bilgi için bkz. Betik Açıklarına Genel Bakış.

<%@ 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>

Açıklamalar

sınıfının yöntemleri ve özellikleri HttpRequest , , HttpContextPageve UserControl sınıflarının HttpApplicationözellikleri aracılığıyla Request kullanıma sunulur.

, , Formveya koleksiyonlarındaki QueryStringverilere erişmek içinQueryString, özelliğinin örneğinde gösterildiği gibi yazabilirsinizRequest["key"].ServerVariables Cookies

Not

Sınıf üyeleri için Unicode desteği için HttpRequest IIS sürüm 6.0 veya üzeri gerekir.

Oluşturucular

HttpRequest(String, String, String)

Bir HttpRequest nesneyi başlatır.

Özellikler

AcceptTypes

İstemci tarafından desteklenen MIME kabul türlerinden oluşan bir dize dizisi alır.

AnonymousID

Varsa, kullanıcının anonim tanımlayıcısını alır.

ApplicationPath

ASP.NET uygulamasının sunucudaki sanal uygulama kök yolunu alır.

AppRelativeCurrentExecutionFilePath

Uygulama kökünün sanal yolunu alır ve uygulama kökü için tilde (~) gösterimini ("~/page.aspx" içinde olduğu gibi) kullanarak göreli hale getirir.

Browser

İstekte bulunan istemcinin tarayıcı özellikleriyle ilgili bilgileri alır veya ayarlar.

ClientCertificate

Geçerli isteğin istemci güvenlik sertifikasını alır.

ContentEncoding

Varlık gövdesinin karakter kümesini alır veya ayarlar.

ContentLength

İstemci tarafından gönderilen içeriğin uzunluğunu bayt cinsinden belirtir.

ContentType

Gelen isteğin MIME içerik türünü alır veya ayarlar.

Cookies

İstemci tarafından gönderilen tanımlama bilgileri koleksiyonunu alır.

CurrentExecutionFilePath

Geçerli isteğin sanal yolunu alır.

CurrentExecutionFilePathExtension

özelliğinde belirtilen dosya adının uzantısını CurrentExecutionFilePath alır.

FilePath

Geçerli isteğin sanal yolunu alır.

Files

İstemci tarafından karşıya yüklenen dosya koleksiyonunu çok parçalı MIME biçiminde alır.

Filter

Geçerli giriş akışını okurken kullanılacak filtreyi alır veya ayarlar.

Form

Form değişkenlerinden oluşan bir koleksiyon alır.

Headers

HTTP üst bilgilerinden oluşan bir koleksiyon alır.

HttpChannelBinding

ChannelBinding Geçerli HttpWorkerRequest örneğin nesnesini alır.

HttpMethod

İstemci tarafından kullanılan HTTP veri aktarım yöntemini (, veya HEADgibiGETPOST) alır.

InputStream

Gelen HTTP varlık gövdesinin içeriğini alır.

IsAuthenticated

İsteğin kimliğinin doğrulanıp doğrulanmadığını belirten bir değer alır.

IsLocal

İsteğin yerel bilgisayardan olup olmadığını belirten bir değer alır.

IsSecureConnection

HTTP bağlantısının güvenli yuvalar (HTTPS) kullanıp kullanmadığını belirten bir değer alır.

Item[String]

Belirtilen nesneyi , Form, Cookiesveya ServerVariables koleksiyonlarından QueryStringalır.

LogonUserIdentity

WindowsIdentity Geçerli kullanıcının türünü alır.

Params

, , FormCookiesve ServerVariables öğelerinin QueryStringbirleştirilmiş koleksiyonunu alır.

Path

Geçerli isteğin sanal yolunu alır.

PathInfo

URL uzantısına sahip bir kaynağın ek yol bilgilerini alır.

PhysicalApplicationPath

Şu anda yürütülmekte olan sunucu uygulamasının kök dizininin fiziksel dosya sistemi yolunu alır.

PhysicalPath

İstenen URL'ye karşılık gelen fiziksel dosya sistemi yolunu alır.

QueryString

HTTP sorgu dizesi değişkenlerinin koleksiyonunu alır.

RawUrl

Geçerli isteğin ham URL'sini alır.

ReadEntityBodyMode

İstek varlık gövdesinin okunup okunmadığını ve okunduysa nasıl okunduğunu gösteren bir değer alır.

RequestContext

RequestContext Geçerli isteğin örneğini alır.

RequestType

İstemci tarafından kullanılan HTTP veri aktarım yöntemini (GET veya ) alır veya POSTayarlar.

ServerVariables

Web sunucusu değişkenlerinden oluşan bir koleksiyon alır.

TimedOutToken

CancellationToken İstek zaman aşımına uğradıklarında atlayan bir nesne alır.

TlsTokenBindingInfo

TLS belirteci bağlama bilgilerini alır. özelliği, uygulamaların gelişmiş kimlik doğrulaması için gelen HTTP isteklerinden belirteç bilgilerini almasını sağlar.

TotalBytes

Geçerli giriş akışındaki bayt sayısını alır.

Unvalidated

İstek doğrulamasını tetiklemeden HTTP isteği değerlerini alır.

Url

Geçerli isteğin URL'si hakkında bilgi alır.

UrlReferrer

İstemcinin geçerli URL'ye bağlı önceki isteğinin URL'si hakkında bilgi alır.

UserAgent

Sağlanan istemci tarayıcısının ham kullanıcı aracısı dizesini alır. Null olabileceğini lütfen unutmayın.

UserHostAddress

Uzak istemcinin IP ana bilgisayar adresini alır.

UserHostName

Uzak istemcinin DNS adını alır.

UserLanguages

İstemci dili tercihlerinden oluşan sıralanmış bir dize dizisi alır.

Yöntemler

Abort()

Temel alınan TCP bağlantısını zorla sonlandırarak bekleyen G/Ç'nin başarısız olmasına neden olur. Kötü amaçlı bir HTTP istemcisinin saldırısına yanıt olarak bu yöntemi kullanabilirsiniz.

BinaryRead(Int32)

Geçerli giriş akışından belirtilen sayıda bayt için ikili okuma gerçekleştirir.

Equals(Object)

Belirtilen nesnenin geçerli nesneye eşit olup olmadığını belirler.

(Devralındığı yer: Object)
GetBufferedInputStream()

Gelen HTTP varlık gövdesini okumak için kullanılabilecek bir Stream nesne alır.

GetBufferlessInputStream()

Gelen HTTP varlık gövdesini okumak için kullanılabilecek bir Stream nesne alır.

GetBufferlessInputStream(Boolean)

Gelen HTTP varlık gövdesini okumak için kullanılabilecek bir Stream nesne alır ve isteğe bağlı olarak özelliğinde MaxRequestLength ayarlanan istek uzunluğu sınırını devre dışı bırakır.

GetHashCode()

Varsayılan karma işlevi işlevi görür.

(Devralındığı yer: Object)
GetType()

Type Geçerli örneğini alır.

(Devralındığı yer: Object)
InsertEntityBody()

IIS'ye HTTP isteği varlık gövdesinin bir kopyasını sağlar.

InsertEntityBody(Byte[], Int32, Int32)

IIS'ye HTTP isteği varlık gövdesinin bir kopyasını ve istek varlığı nesnesi hakkındaki bilgileri sağlar.

MapImageCoordinates(String)

Gelen görüntü alanı form parametresini uygun x koordinatı ve y koordinatı değerlerine Haritalar.

MapPath(String)

Belirtilen sanal yolu fiziksel bir yola Haritalar.

MapPath(String, String, Boolean)

Belirtilen sanal yolu fiziksel bir yola Haritalar.

MapRawImageCoordinates(String)

Gelen görüntü alanı form parametresini uygun x ve y koordinat değerlerine Haritalar.

MemberwiseClone()

Geçerli Objectöğesinin sığ bir kopyasını oluşturur.

(Devralındığı yer: Object)
SaveAs(String, Boolean)

Http isteğini diske kaydeder.

ToString()

Geçerli nesneyi temsil eden dizeyi döndürür.

(Devralındığı yer: Object)
ValidateInput()

, Formve QueryString özellikleri aracılığıyla erişilen koleksiyonlar için doğrulamanın gerçekleşmesine Cookiesneden olur.

Şunlara uygulanır