HttpContext Classe

Definizione

Incapsula tutte le informazioni specifiche di HTTP relative a una singola richiesta HTTP.

public ref class HttpContext sealed : IServiceProvider
public sealed class HttpContext : IServiceProvider
type HttpContext = class
    interface IServiceProvider
Public NotInheritable Class HttpContext
Implements IServiceProvider
Ereditarietà
HttpContext
Implementazioni

Esempio

Nell'esempio seguente viene illustrato come accedere e visualizzare le proprietà dell'oggetto HttpContext . È possibile accedere al contesto della richiesta HTTP corrente usando la Context proprietà dell'oggetto Page .

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        // The HttpContext associated with the page can be accessed by the Context property.
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        // Use the current HttpContext object to determine if custom errors are enabled.
        sb.Append("Is custom errors enabled: " +
            Context.IsCustomErrorEnabled.ToString() + "<br/>");

        // Use the current HttpContext object to determine if debugging is enabled.
        sb.Append("Is debugging enabled: " +
            Context.IsDebuggingEnabled.ToString() + "<br/>");

        // Use the current HttpContext object to access the current TraceContext object.
        sb.Append("Trace Enabled: " +
            Context.Trace.IsEnabled.ToString() + "<br/>");

        // Use the current HttpContext object to access the current HttpApplicationState object.
        sb.Append("Number of items in Application state: " +
            Context.Application.Count.ToString() + "<br/>");

        // Use the current HttpContext object to access the current HttpSessionState object.
        // Session state may not be configured.
        try
        {
            sb.Append("Number of items in Session state: " +
                Context.Session.Count.ToString() + "<br/>");
        }
        catch
        {
            sb.Append("Session state not enabled. <br/>");
        }

        // Use the current HttpContext object to access the current Cache object.
        sb.Append("Number of items in the cache: " +
            Context.Cache.Count.ToString() + "<br/>");

        // Use the current HttpContext object to determine the timestamp for the current HTTP Request.
        sb.Append("Timestamp for the HTTP request: " +
            Context.Timestamp.ToString() + "<br/>");

        // Assign StringBuilder object to output label.
        OutputLabel.Text = sb.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>HttpContext Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       Using the current HttpContext to get information about the current page.
       <br />
       <asp:Label id="OutputLabel" runat="server"></asp:Label>           
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        ' The HttpContext associated with the page can be accessed by the Context property.
        Dim sb As New System.Text.StringBuilder()

        ' Use the current HttpContext object to determine if custom errors are enabled.
        sb.Append("Is custom errors enabled: " & _
            Context.IsCustomErrorEnabled.ToString() & "<br/>")

        ' Use the current HttpContext object to determine if debugging is enabled.
        sb.Append("Is debugging enabled: " & _
            Context.IsDebuggingEnabled.ToString() & "<br/>")

        ' Use the current HttpContext object to access the current TraceContext object.
        sb.Append("Trace Enabled: " & _
            Context.Trace.IsEnabled.ToString() & "<br/>")

        ' Use the current HttpContext object to access the current HttpApplicationState object.
        sb.Append("Number of items in Application state: " & _
            Context.Application.Count.ToString() & "<br/>")

        ' Use the current HttpContext object to access the current HttpSessionState object.
        ' Session state may not be configured.
        Try
            sb.Append("Number of items in Session state: " & _
                Context.Session.Count.ToString() & "<br/>")
        Catch ex As Exception
            sb.Append("Session state not enabled. <br/>")
        End Try

        ' Use the current HttpContext object to access the current Cache object.
        sb.Append("Number of items in the cache: " & _
            Context.Cache.Count.ToString() & "<br/>")

        ' Use the current HttpContext object to determine the timestamp for the current HTTP Request.
        sb.Append("Timestamp for the HTTP request: " & _
            Context.Timestamp.ToString() & "<br/>")

        ' Assign StringBuilder object to output label.
        OutputLabel.Text = sb.ToString()
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>HttpContext Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       Using the current HttpContext to get information about the current page.
       <br />
       <asp:Label id="OutputLabel" runat="server"></asp:Label>           
    </div>
    </form>
</body>
</html>

Commenti

Le classi che ereditano le IHttpModule interfacce e IHttpHandler vengono fornite un riferimento a un HttpContext oggetto per la richiesta HTTP corrente. L'oggetto fornisce l'accesso alle proprietà intrinseche Request, Responsee Server per la richiesta.

Importante

Questo oggetto è pronto per l'operazione di Garbage Collection al termine di HttpRequest . L'utilizzo dopo il completamento della richiesta può causare un comportamento non definito, ad esempio .NullReferenceException

Questo oggetto è disponibile solo nel thread controllato da ASP.NET. L'utilizzo nei thread in background potrebbe causare un comportamento non definito.

Costruttori

HttpContext(HttpRequest, HttpResponse)

Inizializza una nuova istanza della classe HttpContext usando gli oggetti richiesta e risposta specificati.

HttpContext(HttpWorkerRequest)

Inizializza una nuova istanza della classe HttpContext che usa l'oggetto richiesta di lavoro specificato.

Proprietà

AllErrors

Restituisce una matrice degli errori accumulati durante l'elaborazione di una richiesta HTTP.

AllowAsyncDuringSyncStages

Ottiene o imposta un valore che indica se le operazioni asincrone sono consentite durante l'elaborazione delle parti della richiesta ASP.NET quando non sono previste.

Application

Ottiene l'oggetto HttpApplicationState relativo alla richiesta HTTP corrente.

ApplicationInstance

Ottiene o imposta l'oggetto HttpApplication relativo alla richiesta HTTP corrente.

AsyncPreloadMode

Ottiene o imposta un oggetto che contiene i flag relativi alla modalità di precaricamento asincrona.

Cache

Ottiene l'oggetto Cache per il dominio dell'applicazione corrente.

Current

Ottiene o imposta l'oggetto HttpContext relativo alla richiesta HTTP corrente.

CurrentHandler

Ottiene l'oggetto IHttpHandler che rappresenta il gestore attualmente in esecuzione.

CurrentNotification

Ottiene un valore RequestNotification che indica l'evento HttpApplication attualmente in elaborazione.

Error

Restituisce il primo errore, se presente, accumulato durante l'elaborazione di una richiesta HTTP.

Handler

Ottiene o imposta l'oggetto IHttpHandler responsabile dell'elaborazione della richiesta HTTP.

IsCustomErrorEnabled

Restituisce un valore che indica se gli errori personalizzati sono stati attivati per la richiesta HTTP corrente.

IsDebuggingEnabled

Restituisce un valore che indica se la richiesta HTTP corrente è in modalità di debug.

IsPostNotification

Ottiene un valore che rappresenta il punto di elaborazione corrente nella pipeline ASP.NET subito dopo il completamento dell'elaborazione di un evento HttpApplication.

IsWebSocketRequest

Ottiene un valore che indica se la richiesta è una richiesta AspNetWebSocket.

IsWebSocketRequestUpgrading

Ottiene un valore che indica se si sta eseguendo l'aggiornamento della connessione da una connessione HTTP a una connessione AspNetWebSocket.

Items

Ottiene una raccolta chiave/valore che è possibile usare per organizzare e condividere dati tra un'interfaccia IHttpModule e un'interfaccia IHttpHandler durante una richiesta HTTP.

PageInstrumentation

Ottiene un riferimento all'istanza del servizio di strumentazione pagina per questa richiesta.

PreviousHandler

Ottiene l'oggetto IHttpHandler relativo al gestore padre.

Profile

Ottiene l'oggetto ProfileBase relativo al profilo utente corrente.

Request

Ottiene l'oggetto HttpRequest relativo alla richiesta HTTP corrente.

Response

Restituisce l'oggetto HttpResponse relativo alla risposta HTTP corrente.

Server

Restituisce l'oggetto HttpServerUtility che fornisce i metodi usati nell'elaborazione delle richieste Web.

Session

Ottiene l'oggetto HttpSessionState relativo alla richiesta HTTP corrente.

SkipAuthorization

Ottiene o imposta un valore che specifica se l'oggetto UrlAuthorizationModule deve ignorare il controllo delle autorizzazioni per la richiesta corrente.

ThreadAbortOnTimeout

Ottiene o imposta un valore che specifica se il runtime ASP.NET deve chiamare Abort() sul thread che sta rispondendo a questa richiesta quando la richiesta scade.

Timestamp

Restituisce il timestamp iniziale della richiesta HTTP corrente.

Trace

Restituisce l'oggetto TraceContext relativo alla risposta HTTP corrente.

User

Ottiene o imposta le informazioni sulla sicurezza per la richiesta HTTP corrente.

WebSocketNegotiatedProtocol

Ottiene il protocollo negoziato inviato dal server al client per una connessione AspNetWebSocket.

WebSocketRequestedProtocols

Ottiene l'elenco ordinato dei protocolli richiesti dal client.

Metodi

AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>)

Accetta una richiesta AspNetWebSocket con la funzione utente specificata.

AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>, AspNetWebSocketOptions)

Accetta una richiesta AspNetWebSocket con la funzione utente specificata e l'oggetto delle opzioni.

AddError(Exception)

Aggiunge un'eccezione alla raccolta di eccezioni per la richiesta HTTP corrente.

AddOnRequestCompleted(Action<HttpContext>)

Genera un evento virtuale che si verifica quando la parte HTTP della richiesta sta terminando.

ClearError()

Cancella tutti gli errori relativi alla richiesta HTTP corrente.

DisposeOnPipelineCompleted(IDisposable)

Consente di chiamare il metodo Dispose() di un oggetto quando la parte della connessione AspNetWebSocket della richiesta viene completata.

Equals(Object)

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

(Ereditato da Object)
GetAppConfig(String)
Obsoleta.

Restituisce le informazioni sulla configurazione richieste per l'applicazione in uso.

GetConfig(String)
Obsoleta.

Restituisce le informazioni sulla configurazione relative alla richiesta HTTP corrente.

GetGlobalResourceObject(String, String)

Ottiene un oggetto risorsa a livello di applicazione basato sulle proprietà ClassKey e ResourceKey specificate.

GetGlobalResourceObject(String, String, CultureInfo)

Ottiene un oggetto risorsa a livello di applicazione basato sulle proprietà ClassKey e ResourceKey specificate e sull'oggetto CultureInfo.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLocalResourceObject(String, String)

Ottiene un oggetto della risorsa a livello di pagina basato sulle proprietà VirtualPath e ResourceKey specificate.

GetLocalResourceObject(String, String, CultureInfo)

Ottiene un oggetto della risorsa a livello di pagina basato sulle proprietà VirtualPath e ResourceKey specificate e sull'oggetto CultureInfo.

GetSection(String)

Ottiene una sezione di configurazione specificata per la configurazione predefinita dell'applicazione corrente.

GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
RemapHandler(IHttpHandler)

Consente di specificare un gestore per la richiesta.

RewritePath(String)

Riscrive l'URL con il percorso specificato.

RewritePath(String, Boolean)

Riscrive l'URL con il percorso specificato e un valore booleano che specifica se il percorso virtuale per le risorse del server è stato modificato.

RewritePath(String, String, String)

Riscrive l'URL usando il percorso specificato, le informazioni sul percorso e le informazioni sulla stringa di query.

RewritePath(String, String, String, Boolean)

Riscrive l'URL con il percorso virtuale specificato, informazioni sul percorso, informazioni sulla stringa di query e un valore booleano che specifica se il percorso del file del client è impostato sul percorso di riscrittura.

SetSessionStateBehavior(SessionStateBehavior)

Imposta il tipo di comportamento dello stato di sessione necessario per supportare una richiesta HTTP.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Implementazioni dell'interfaccia esplicita

IServiceProvider.GetService(Type)

Restituisce un oggetto per il tipo di servizio corrente.

Si applica a

Vedi anche