HttpRequest Klasa

Definicja

Umożliwia ASP.NET odczytywanie wartości HTTP wysyłanych przez klienta podczas żądania internetowego.

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

Przykłady

Poniższe przykłady uzyskują dostęp do HttpRequest wystąpienia bieżącego żądania przy użyciu Request właściwości Page klasy .

Aby uzyskać dostęp do danych z kolekcji , Form, CookieslubServerVariables, można użyć uproszczonej QueryStringskładni. Możesz napisać plik Request["key"].

W pierwszym przykładzie pokazano, jak pobrać wartość ciągu zapytania podczas ładowania strony.

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

W następnym przykładzie pokazano, jak sprawdzić, czy żądanie zostało uwierzytelnione, i pobrać pierwotny adres 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

Projekt witryny sieci Web programu Visual Studio z kodem źródłowym jest dostępny do dołączenia do tego tematu: Pobierz.

W tym przykładzie użyto StreamWriter klasy do zapisania wartości kilku HttpRequest właściwości klasy w pliku. W przypadku właściwości, które są ciągiem typu, wartości są kodowane w formacie HTML, ponieważ są zapisywane w pliku. Właściwości reprezentujące kolekcję są przekazywane w pętli, a każda para klucz/wartość, którą zawiera, jest zapisywana w pliku.

Ważne

Ten przykład zawiera pole tekstowe, które akceptuje dane wejściowe użytkownika, co jest potencjalnym zagrożeniem bezpieczeństwa. Domyślnie ASP.NET strony sieci Web sprawdzają, czy dane wejściowe użytkownika nie zawierają skryptów ani elementów HTML. Aby uzyskać więcej informacji, zobacz Script Exploits Overview (Omówienie luk w zabezpieczeniach skryptów).

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

Uwagi

Metody i właściwości HttpRequest klasy są udostępniane za pośrednictwem Request właściwości HttpApplicationklas , HttpContext, Pagei UserControl .

Aby uzyskać dostęp do danych z QueryStringkolekcji , Form, Cookieslub ServerVariables , możesz napisać Request["key"], jak pokazano w przykładzie QueryString dla właściwości .

Uwaga

Obsługa formatu Unicode dla HttpRequest składowych klas wymaga usług IIS w wersji 6.0 lub nowszej.

Konstruktory

HttpRequest(String, String, String)

Inicjuje HttpRequest obiekt.

Właściwości

AcceptTypes

Pobiera tablicę ciągów obsługiwanych przez klienta typów akceptowanych przez program MIME.

AnonymousID

Pobiera identyfikator anonimowy użytkownika, jeśli istnieje.

ApplicationPath

Pobiera ścieżkę główną aplikacji wirtualnej aplikacji ASP.NET na serwerze.

AppRelativeCurrentExecutionFilePath

Pobiera ścieżkę wirtualną katalogu głównego aplikacji i tworzy ją względną przy użyciu notacji tyldy (~) dla katalogu głównego aplikacji (jak w pliku "~/page.aspx").

Browser

Pobiera lub ustawia informacje o możliwościach przeglądarki klienta żądającego.

ClientCertificate

Pobiera certyfikat zabezpieczeń klienta bieżącego żądania.

ContentEncoding

Pobiera lub ustawia zestaw znaków treści jednostki.

ContentLength

Określa długość zawartości wysyłanej przez klienta w bajtach.

ContentType

Pobiera lub ustawia typ zawartości MIME żądania przychodzącego.

Cookies

Pobiera kolekcję plików cookie wysyłanych przez klienta.

CurrentExecutionFilePath

Pobiera ścieżkę wirtualną bieżącego żądania.

CurrentExecutionFilePathExtension

Pobiera rozszerzenie nazwy pliku określonej we CurrentExecutionFilePath właściwości .

FilePath

Pobiera ścieżkę wirtualną bieżącego żądania.

Files

Pobiera kolekcję plików przekazanych przez klienta w formacie MIME wieloczęściowym.

Filter

Pobiera lub ustawia filtr do użycia podczas odczytywania bieżącego strumienia wejściowego.

Form

Pobiera kolekcję zmiennych formularza.

Headers

Pobiera kolekcję nagłówków HTTP.

HttpChannelBinding

ChannelBinding Pobiera obiekt bieżącego HttpWorkerRequest wystąpienia.

HttpMethod

Pobiera metodę transferu danych HTTP (na przykład GET, POSTlub HEAD) używaną przez klienta.

InputStream

Pobiera zawartość przychodzącej treści jednostki HTTP.

IsAuthenticated

Pobiera wartość wskazującą, czy żądanie zostało uwierzytelnione.

IsLocal

Pobiera wartość wskazującą, czy żądanie pochodzi z komputera lokalnego.

IsSecureConnection

Pobiera wartość wskazującą, czy połączenie HTTP korzysta z bezpiecznych gniazd (czyli HTTPS).

Item[String]

Pobiera określony obiekt z QueryStringkolekcji , Form, Cookieslub ServerVariables .

LogonUserIdentity

WindowsIdentity Pobiera typ bieżącego użytkownika.

Params

Pobiera połączoną kolekcję QueryStringelementów , , CookiesFormi ServerVariables .

Path

Pobiera ścieżkę wirtualną bieżącego żądania.

PathInfo

Pobiera dodatkowe informacje o ścieżce dla zasobu z rozszerzeniem adresu URL.

PhysicalApplicationPath

Pobiera fizyczną ścieżkę systemu plików aktualnie wykonywanego katalogu głównego aplikacji serwera.

PhysicalPath

Pobiera fizyczną ścieżkę systemu plików odpowiadającą żądanemu adresowi URL.

QueryString

Pobiera kolekcję zmiennych ciągu zapytania HTTP.

RawUrl

Pobiera pierwotny adres URL bieżącego żądania.

ReadEntityBodyMode

Pobiera wartość wskazującą, czy treść jednostki żądania została odczytowana, a jeśli tak, sposób jej odczytywania.

RequestContext

RequestContext Pobiera wystąpienie bieżącego żądania.

RequestType

Pobiera lub ustawia metodę transferu danych HTTP (GET lub POST) używaną przez klienta.

ServerVariables

Pobiera kolekcję zmiennych serwera sieci Web.

TimedOutToken

Pobiera obiekt, który jest potknięty CancellationToken po przekroczeniu limitu czasu żądania.

TlsTokenBindingInfo

Pobiera informacje o powiązaniu tokenu TLS. Właściwość umożliwia aplikacjom pobieranie informacji o tokenie z przychodzących żądań HTTP na potrzeby rozszerzonego uwierzytelniania.

TotalBytes

Pobiera liczbę bajtów w bieżącym strumieniu wejściowym.

Unvalidated

Pobiera wartości żądania HTTP bez wyzwalania weryfikacji żądania.

Url

Pobiera informacje o adresie URL bieżącego żądania.

UrlReferrer

Pobiera informacje o adresie URL poprzedniego żądania klienta połączonego z bieżącym adresem URL.

UserAgent

Pobiera nieprzetworzone ciągi agenta użytkownika w podanej przeglądarce klienta. Pamiętaj, że może to być wartość null.

UserHostAddress

Pobiera adres hosta IP klienta zdalnego.

UserHostName

Pobiera nazwę DNS klienta zdalnego.

UserLanguages

Pobiera posortowaną tablicę ciągów preferencji języka klienta.

Metody

Abort()

Wymuszone zakończenie bazowego połączenia TCP powoduje niepowodzenie operacji we/wy zaległych operacji we/wy. Ta metoda może być używana w odpowiedzi na atak złośliwego klienta HTTP.

BinaryRead(Int32)

Wykonuje odczyt binarny określonej liczby bajtów z bieżącego strumienia wejściowego.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetBufferedInputStream()

Stream Pobiera obiekt, który może służyć do odczytywania przychodzącej treści jednostki HTTP.

GetBufferlessInputStream()

Stream Pobiera obiekt, który może służyć do odczytywania przychodzącej treści jednostki HTTP.

GetBufferlessInputStream(Boolean)

Stream Pobiera obiekt, który może służyć do odczytywania przychodzącej treści jednostki HTTP, opcjonalnie wyłączając limit długości żądania ustawiony we MaxRequestLength właściwości .

GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
InsertEntityBody()

Dostarcza usługom IIS kopię treści jednostki żądania HTTP.

InsertEntityBody(Byte[], Int32, Int32)

Dostarcza usługom IIS kopię treści jednostki żądania HTTP oraz informacje o obiekcie jednostki żądania.

MapImageCoordinates(String)

Mapuje przychodzący parametr formularza pola obrazu na odpowiednie wartości współrzędnych x i współrzędnych y.

MapPath(String)

Mapuje określoną ścieżkę wirtualną na ścieżkę fizyczną.

MapPath(String, String, Boolean)

Mapuje określoną ścieżkę wirtualną na ścieżkę fizyczną.

MapRawImageCoordinates(String)

Mapuje parametr formularza pola obrazu przychodzącego na odpowiednie wartości współrzędnych x i y.

MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
SaveAs(String, Boolean)

Zapisuje żądanie HTTP na dysku.

ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)
ValidateInput()

Powoduje, że sprawdzanie poprawności kolekcji, do których uzyskuje się dostęp za pośrednictwem Cookieswłaściwości , Formi QueryString .

Dotyczy