HttpRequest Classe

Definizione

Consente ad ASP.NET di leggere i valori HTTP inviati da un client durante una richiesta Web.

public ref class HttpRequest sealed
public sealed class HttpRequest
type HttpRequest = class
Public NotInheritable Class HttpRequest
Ereditarietà
HttpRequest

Esempio

Gli esempi seguenti accedono all'istanza HttpRequest per la richiesta corrente usando la Request proprietà della Page classe .

È possibile usare la sintassi semplificata per accedere ai dati dalle QueryStringraccolte , Form, Cookieso ServerVariables . È possibile scrivere Request["key"].

Nel primo esempio viene illustrato come recuperare un valore stringa di query durante il caricamento di una pagina.

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

Nell'esempio seguente viene illustrato come verificare se la richiesta è autenticata e recuperare l'URL non elaborato.

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

È disponibile un progetto di sito Web Visual Studio con codice sorgente associato a questo argomento: Download.

In questo esempio viene utilizzata la StreamWriter classe per scrivere i valori di diverse HttpRequest proprietà di classe in un file. Per le proprietà di tipo stringa, i valori vengono codificati in FORMATO HTML mentre vengono scritti nel file. Le proprietà che rappresentano una raccolta vengono sottoposte a ciclo continuo e ogni coppia chiave/valore che contengono viene scritta nel file.

Importante

L'esempio include una casella di testo che accetta l'input dell'utente e rappresenta quindi una potenziale minaccia alla sicurezza. Per impostazione predefinita, le pagine Web ASP.NET verificano che l'input dell'utente non includa script o elementi HTML. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.

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

Commenti

I metodi e le proprietà della HttpRequest classe vengono esposti tramite le Request proprietà delle HttpApplicationclassi , HttpContext, Pagee UserControl .

Per accedere ai dati dalle QueryStringraccolte , Form, Cookieso ServerVariables , è possibile scrivere Request["key"], come illustrato nell'esempio per la QueryString proprietà .

Nota

Il supporto Unicode per HttpRequest i membri della classe richiede IIS versione 6.0 o successiva.

Costruttori

HttpRequest(String, String, String)

Inizializza un oggetto HttpRequest.

Proprietà

AcceptTypes

Ottiene una matrice di stringhe di tipi di accettazione MIME supportati dal client.

AnonymousID

Ottiene l'identificatore anonimo per l'utente, se presente.

ApplicationPath

Ottiene il percorso radice dell'applicazione virtuale dell'applicazione ASP.NET sul server.

AppRelativeCurrentExecutionFilePath

Ottiene il percorso virtuale della radice dell'applicazione e lo converte in relativo tramite la notazione tilde (~) per la radice dell'applicazione, come in "~/page.aspx".

Browser

Ottiene o imposta informazioni sulle funzionalità del browser del client richiedente.

ClientCertificate

Ottiene il certificato di sicurezza del client della richiesta corrente.

ContentEncoding

Ottiene o imposta il set di caratteri del corpo dell'entità.

ContentLength

Specifica la lunghezza, in byte, del contenuto inviato dal client.

ContentType

Ottiene o imposta il tipo di contenuto MIME della richiesta in ingresso.

Cookies

Ottiene la raccolta dei cookie inviati dal client.

CurrentExecutionFilePath

Ottiene il percorso virtuale della richiesta corrente.

CurrentExecutionFilePathExtension

Ottiene l'estensione del nome file specificato nella proprietà CurrentExecutionFilePath.

FilePath

Ottiene il percorso virtuale della richiesta corrente.

Files

Ottiene la raccolta di file caricati dal client, in formato MIME multipart.

Filter

Ottiene o imposta il filtro da usare per la lettura del flusso di input corrente.

Form

Ottiene una raccolta di variabili form.

Headers

Ottiene una raccolta di intestazioni HTTP.

HttpChannelBinding

Ottiene l'oggetto ChannelBinding dell'istanza corrente di HttpWorkerRequest.

HttpMethod

Ottiene il metodo di trasferimento dei dati HTTP, ad esempio GET, POST o HEAD, usato dal client.

InputStream

Ottiene il contenuto del corpo dell'entità HTTP in ingresso.

IsAuthenticated

Ottiene un valore che indica se la richiesta è stata autenticata.

IsLocal

Ottiene un valore che indica se la richiesta proviene dal computer locale.

IsSecureConnection

Ottiene un valore che indica se per la connessione HTTP viene usato Secure Sockets, ovvero HTTPS.

Item[String]

Ottiene l'oggetto specificato dalle raccolte QueryString, Form, Cookies o ServerVariables.

LogonUserIdentity

Ottiene il tipo WindowsIdentity per l'utente corrente.

Params

Ottiene una raccolta combinata di elementi QueryString, Form, Cookies e ServerVariables.

Path

Ottiene il percorso virtuale della richiesta corrente.

PathInfo

Ottiene informazioni aggiuntive sul percorso di una risorsa con estensione URL.

PhysicalApplicationPath

Ottiene il percorso fisico del file system della directory radice dell'applicazione server attualmente in esecuzione.

PhysicalPath

Ottiene il percorso fisico del file system corrispondente all'URL richiesto.

QueryString

Ottiene la raccolta di variabili di tipo stringa di query HTTP.

RawUrl

Ottiene l'URL non elaborato della richiesta corrente.

ReadEntityBodyMode

Ottiene un valore che indica se il corpo dell'entità di richiesta è stato letto e, in caso affermativo, la modalità di lettura.

RequestContext

Ottiene l'istanza di RequestContext della richiesta corrente.

RequestType

Ottiene o imposta il metodo di trasferimento dei dati HTTP (GET o POST) usato dal client.

ServerVariables

Ottiene una raccolta di variabili server Web.

TimedOutToken

Ottiene un oggetto CancellationToken che viene attivato quando scade una richiesta.

TlsTokenBindingInfo

Ottiene le informazioni di associazione dei token TLS. La proprietà consente alle applicazioni di recuperare informazioni sul token da richieste HTTP in ingresso per l'autenticazione avanzata.

TotalBytes

Ottiene il numero di byte nel flusso di input corrente.

Unvalidated

Ottiene i valori delle richieste HTTP senza attivare la convalida delle richieste.

Url

Ottiene informazioni sull'URL della richiesta corrente.

UrlReferrer

Ottiene informazioni sull'URL della richiesta precedente del client collegato all'URL corrente.

UserAgent

Ottiene la stringa dell'agente utente non elaborata del browser client specificato. Si noti che può essere Null.

UserHostAddress

Ottiene l'indirizzo host IP del client remoto.

UserHostName

Ottiene il nome DNS del client remoto.

UserLanguages

Ottiene una matrice di stringhe ordinata di preferenze linguistiche del client.

Metodi

Abort()

Termina forzatamente la connessione TCP sottostante, causando l'esito negativo di eventuali operazioni di I/O. È possibile usare questo metodo in risposta all'attacco di un client HTTP dannoso.

BinaryRead(Int32)

Esegue una lettura binaria di un determinato numero di byte provenienti dal flusso di input corrente.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetBufferedInputStream()

Ottiene un oggetto Stream che può essere usato per leggere il corpo dell'entità HTTP in ingresso.

GetBufferlessInputStream()

Ottiene un oggetto Stream che può essere usato per leggere il corpo dell'entità HTTP in ingresso.

GetBufferlessInputStream(Boolean)

Ottiene un oggetto Stream che può essere usato per leggere il corpo dell'entità HTTP in ingresso, disabilitando facoltativamente il limite di lunghezza della richiesta impostato nella proprietà MaxRequestLength.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
InsertEntityBody()

Fornisce a IIS una copia del corpo dell'entità di richiesta HTTP.

InsertEntityBody(Byte[], Int32, Int32)

Fornisce a IIS una copia del corpo dell'entità di richiesta HTTP nonché le informazioni sull'oggetto entità di richiesta.

MapImageCoordinates(String)

Esegue il mapping di un parametro form del campo immagine in ingresso ai valori appropriati delle coordinate x e y.

MapPath(String)

Esegue il mapping del percorso virtuale specificato a un percorso fisico.

MapPath(String, String, Boolean)

Esegue il mapping del percorso virtuale specificato a un percorso fisico.

MapRawImageCoordinates(String)

Esegue il mapping di un parametro form del campo immagine in ingresso ai valori appropriati delle coordinate x e y.

MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
SaveAs(String, Boolean)

Salva una richiesta HTTP su disco.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
ValidateInput()

Determina la convalida delle raccolte accessibili mediante le proprietà Cookies, Form e QueryString.

Si applica a