HttpRequest Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Consente 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 , FormCookies, o ServerVariables . È possibile scrivere Request["key"].
Il primo esempio mostra come recuperare un valore della 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
In questo esempio viene utilizzata la StreamWriter classe per scrivere i valori di diverse HttpRequest proprietà della classe in un file. Per le proprietà di tipo string, 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
In questo esempio è presente una casella di testo che accetta l'input dell'utente, che rappresenta una potenziale minaccia per la sicurezza. Per impostazione predefinita, ASP.NET pagine Web verificare che l'input dell'utente non includa elementi SCRIPT o HTML. Per altre informazioni, vedere Cenni preliminari sugli exploit di 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 , HttpContextPage, e UserControl .
Per accedere ai dati dalle QueryStringraccolte , Form, Cookieso ServerVariables , è possibile scrivere Request["key"], come illustrato nell'esempio per la QueryString proprietà .
Annotazioni
Il supporto Unicode per HttpRequest i membri della classe richiede IIS versione 6.0 o successiva.
Costruttori
| Nome | Descrizione |
|---|---|
| HttpRequest(String, String, String) |
Inizializza un HttpRequest oggetto . |
Proprietà
| Nome | Descrizione |
|---|---|
| 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 nel server. |
| AppRelativeCurrentExecutionFilePath |
Ottiene il percorso virtuale della radice dell'applicazione e lo rende relativo usando 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 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 una raccolta di cookie inviati dal client. |
| CurrentExecutionFilePath |
Ottiene il percorso virtuale della richiesta corrente. |
| CurrentExecutionFilePathExtension |
Ottiene l'estensione del nome file specificato nella CurrentExecutionFilePath proprietà . |
| 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 utilizzare durante la lettura del flusso di input corrente. |
| Form |
Ottiene una raccolta di variabili di modulo. |
| Headers |
Ottiene una raccolta di intestazioni HTTP. |
| HttpChannelBinding |
Ottiene l'oggetto ChannelBinding dell'istanza corrente HttpWorkerRequest . |
| HttpMethod |
Ottiene il metodo di trasferimento dei dati HTTP , ad esempio |
| 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 la connessione HTTP usa socket sicuri, ovvero HTTPS. |
| Item[String] |
Ottiene l'oggetto specificato dagli QueryStringinsiemi , FormCookies, o ServerVariables . |
| LogonUserIdentity |
Ottiene il WindowsIdentity tipo per l'utente corrente. |
| Params |
Ottiene una raccolta combinata di QueryStringelementi , Form, Cookiese ServerVariables . |
| Path |
Ottiene il percorso virtuale della richiesta corrente. |
| PathInfo |
Ottiene le informazioni aggiuntive sul percorso per una risorsa con un'estensione URL. |
| PhysicalApplicationPath |
Ottiene il percorso fisico del file system della directory radice dell'applicazione server attualmente in esecuzione. |
| PhysicalPath |
Ottiene il percorso del file system fisico corrispondente all'URL richiesto. |
| QueryString |
Ottiene la raccolta di variabili della stringa di query HTTP. |
| RawUrl |
Ottiene l'URL non elaborato della richiesta corrente. |
| ReadEntityBodyMode |
Ottiene un valore che indica se il corpo dell'entità richiesta è stato letto e, in tal caso, come è stato letto. |
| RequestContext |
Ottiene l'istanza RequestContext della richiesta corrente. |
| RequestType |
Ottiene o imposta il metodo di trasferimento dati HTTP ( |
| ServerVariables |
Ottiene una raccolta di variabili del server Web. |
| TimedOutToken |
Ottiene un CancellationToken oggetto che viene ritagliato quando si verifica il timeout di una richiesta. |
| TlsTokenBindingInfo |
Ottiene le informazioni sull'associazione di token TLS. La proprietà consente alle applicazioni di recuperare informazioni sul token dalle richieste HTTP in ingresso per l'autenticazione avanzata. |
| TotalBytes |
Ottiene il numero di byte nel flusso di input corrente. |
| Unvalidated |
Ottiene i valori della richiesta HTTP senza attivare la convalida della richiesta. |
| Url |
Ottiene informazioni sull'URL della richiesta corrente. |
| UrlReferrer |
Ottiene informazioni sull'URL della richiesta precedente del client collegata all'URL corrente. |
| UserAgent |
Ottiene la stringa dell'agente utente non elaborato del browser client fornito. Si noti che potrebbe 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 delle preferenze di lingua client. |
Metodi
| Nome | Descrizione |
|---|---|
| Abort() |
Termina forzatamente la connessione TCP sottostante, causando un errore di I/O in sospeso. È possibile usare questo metodo in risposta a un attacco da parte di un client HTTP dannoso. |
| BinaryRead(Int32) |
Esegue una lettura binaria di un numero specificato di byte dal flusso di input corrente. |
| Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente. (Ereditato da Object) |
| GetBufferedInputStream() |
Ottiene un Stream oggetto che può essere utilizzato per leggere il corpo dell'entità HTTP in ingresso. |
| GetBufferlessInputStream() |
Ottiene un Stream oggetto che può essere utilizzato per leggere il corpo dell'entità HTTP in ingresso. |
| GetBufferlessInputStream(Boolean) |
Ottiene un Stream oggetto che può essere utilizzato per leggere il corpo dell'entità HTTP in ingresso, disabilitando facoltativamente il limite di lunghezza della richiesta impostato nella MaxRequestLength proprietà . |
| GetHashCode() |
Funge da funzione hash predefinita. (Ereditato da Object) |
| GetType() |
Ottiene il Type dell'istanza corrente. (Ereditato da Object) |
| InsertEntityBody() |
Fornisce IIS con una copia del corpo dell'entità richiesta HTTP. |
| InsertEntityBody(Byte[], Int32, Int32) |
Fornisce IIS con una copia del corpo dell'entità richiesta HTTP e con informazioni sull'oggetto entità richiesta. |
| MapImageCoordinates(String) |
Esegue il mapping di un parametro modulo image-field in ingresso ai valori appropriati di coordinate x e coordinate y. |
| MapPath(String, String, Boolean) |
Esegue il mapping del percorso virtuale specificato a un percorso fisico. |
| MapPath(String) |
Esegue il mapping del percorso virtuale specificato a un percorso fisico. |
| MapRawImageCoordinates(String) |
Esegue il mapping di un parametro modulo di campo immagine in ingresso in valori di coordinate x e y appropriati. |
| MemberwiseClone() |
Crea una copia superficiale del Objectcorrente. (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 l'esecuzione della convalida per le raccolte a cui si accede tramite le Cookiesproprietà , Forme QueryString . |