Condividi tramite


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 . L'accesso al contesto della richiesta HTTP corrente viene eseguito 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 dell'oggetto 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

Nome Descrizione
HttpContext(HttpRequest, HttpResponse)

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

HttpContext(HttpWorkerRequest)

Inizializza una nuova istanza della HttpContext classe che utilizza l'oggetto worker-request specificato.

Proprietà

Nome Descrizione
AllErrors

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

AllowAsyncDuringSyncStages

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

Application

Ottiene l'oggetto HttpApplicationState per la richiesta HTTP corrente.

ApplicationInstance

Ottiene o imposta l'oggetto HttpApplication per la richiesta HTTP corrente.

AsyncPreloadMode

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

Cache

Ottiene l'oggetto Cache per il dominio applicazione corrente.

Current

Ottiene o imposta l'oggetto HttpContext per la richiesta HTTP corrente.

CurrentHandler

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

CurrentNotification

Ottiene un RequestNotification valore che indica l'evento corrente HttpApplication che sta elaborando.

Error

Ottiene il primo errore (se presente) accumulato durante l'elaborazione delle richieste HTTP.

Handler

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

IsCustomErrorEnabled

Ottiene un valore che indica se gli errori personalizzati sono abilitati per la richiesta HTTP corrente.

IsDebuggingEnabled

Ottiene 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 HttpApplication evento.

IsWebSocketRequest

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

IsWebSocketRequestUpgrading

Ottiene un valore che indica se la connessione viene aggiornata da una connessione HTTP a una AspNetWebSocket connessione.

Items

Ottiene una raccolta chiave/valore che può essere utilizzata 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 per il gestore padre.

Profile

Ottiene l'oggetto ProfileBase per il profilo utente corrente.

Request

Ottiene l'oggetto HttpRequest per la richiesta HTTP corrente.

Response

Ottiene l'oggetto HttpResponse per la risposta HTTP corrente.

Server

Ottiene l'oggetto che fornisce metodi utilizzati per l'elaborazione HttpServerUtility delle richieste Web.

Session

Ottiene l'oggetto HttpSessionState per la richiesta HTTP corrente.

SkipAuthorization

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

ThreadAbortOnTimeout

Ottiene o imposta un valore che specifica se il runtime ASP.NET deve chiamare Abort() sul thread che esegue la manutenzione di questa richiesta quando si verifica il timeout della richiesta.

Timestamp

Ottiene il timestamp iniziale della richiesta HTTP corrente.

Trace

Ottiene l'oggetto TraceContext per la risposta HTTP corrente.

User

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

WebSocketNegotiatedProtocol

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

WebSocketRequestedProtocols

Ottiene l'elenco ordinato di protocolli richiesti dal client.

Metodi

Nome Descrizione
AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>, AspNetWebSocketOptions)

Accetta una AspNetWebSocket richiesta utilizzando la funzione utente e l'oggetto opzioni specificati.

AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>)

Accetta una AspNetWebSocket richiesta usando la funzione utente specificata.

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 termina.

ClearError()

Cancella tutti gli errori per la richiesta HTTP corrente.

DisposeOnPipelineCompleted(IDisposable)

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

Equals(Object)

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

(Ereditato da Object)
GetAppConfig(String)
Obsoleti.

Restituisce le informazioni di configurazione richieste per l'applicazione corrente.

GetConfig(String)
Obsoleti.

Restituisce le informazioni di configurazione richieste per la richiesta HTTP corrente.

GetGlobalResourceObject(String, String, CultureInfo)

Ottiene un oggetto risorsa a livello di applicazione in base alle proprietà e ResourceKey specificate ClassKey e all'oggetto CultureInfo .

GetGlobalResourceObject(String, String)

Ottiene un oggetto risorsa a livello di applicazione in base alle proprietà e ResourceKey specificateClassKey.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLocalResourceObject(String, String, CultureInfo)

Ottiene un oggetto risorsa a livello di pagina in base alle proprietà e ResourceKey specificate VirtualPath e all'oggetto CultureInfo .

GetLocalResourceObject(String, String)

Ottiene un oggetto risorsa a livello di pagina in base alle proprietà e ResourceKey specificateVirtualPath.

GetSection(String)

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

GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
RemapHandler(IHttpHandler)

Consente di specificare un gestore per la richiesta.

RewritePath(String, Boolean)

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

RewritePath(String, String, String, Boolean)

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

RewritePath(String, String, String)

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

RewritePath(String)

Riscrive l'URL usando il percorso specificato.

SetSessionStateBehavior(SessionStateBehavior)

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

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Implementazioni dell'interfaccia esplicita

Nome Descrizione
IServiceProvider.GetService(Type)

Restituisce un oggetto per il tipo di servizio corrente.

Si applica a

Vedi anche