HttpContext HttpContext HttpContext HttpContext Class

Definition

Encapsulates all HTTP-specific information about an individual HTTP request.

public ref class HttpContext sealed : IServiceProvider
public sealed class HttpContext : IServiceProvider
type HttpContext = class
    interface IServiceProvider
Public NotInheritable Class HttpContext
Implements IServiceProvider
Inheritance
HttpContextHttpContextHttpContextHttpContext
Implements

Examples

The following example demonstrates how to access and display properties of the HttpContext object. The context of the current HTTP request is accessed by using the Context property of the Page object.

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

Remarks

Classes that inherit the IHttpModule and IHttpHandler interfaces are provided a reference to an HttpContext object for the current HTTP request. The object provides access to the intrinsic Request, Response, and Server properties for the request.

Important

This object is ready for garbage collection when the HttpRequest is completed. Its usage after the request completes could lead to undefined behavior, such as a NullReferenceException.

This object is only available in the thread controlled by ASP.NET. Usage in background threads could lead to undefined behavior.

Constructors

HttpContext(HttpRequest, HttpResponse) HttpContext(HttpRequest, HttpResponse) HttpContext(HttpRequest, HttpResponse) HttpContext(HttpRequest, HttpResponse)

Initializes a new instance of the HttpContext class by using the specified request and response objects.

HttpContext(HttpWorkerRequest) HttpContext(HttpWorkerRequest) HttpContext(HttpWorkerRequest) HttpContext(HttpWorkerRequest)

Initializes a new instance of the HttpContext class that uses the specified worker-request object.

Properties

AllErrors AllErrors AllErrors AllErrors

Gets an array of errors accumulated while processing an HTTP request.

AllowAsyncDuringSyncStages AllowAsyncDuringSyncStages AllowAsyncDuringSyncStages AllowAsyncDuringSyncStages

Gets or sets a value that indicates whether asynchronous operations are allowed during parts of ASP.NET request processing when they are not expected.

Application Application Application Application

Gets the HttpApplicationState object for the current HTTP request.

ApplicationInstance ApplicationInstance ApplicationInstance ApplicationInstance

Gets or sets the HttpApplication object for the current HTTP request.

AsyncPreloadMode AsyncPreloadMode AsyncPreloadMode AsyncPreloadMode

Gets or sets an object that contains flags that pertain to asynchronous preload mode.

Cache Cache Cache Cache

Gets the Cache object for the current application domain.

Current Current Current Current

Gets or sets the HttpContext object for the current HTTP request.

CurrentHandler CurrentHandler CurrentHandler CurrentHandler

Gets the IHttpHandler object that represents the currently executing handler.

CurrentNotification CurrentNotification CurrentNotification CurrentNotification

Gets a RequestNotification value that indicates the current HttpApplication event that is processing.

Error Error Error Error

Gets the first error (if any) accumulated during HTTP request processing.

Handler Handler Handler Handler

Gets or sets the IHttpHandler object responsible for processing the HTTP request.

IsCustomErrorEnabled IsCustomErrorEnabled IsCustomErrorEnabled IsCustomErrorEnabled

Gets a value indicating whether custom errors are enabled for the current HTTP request.

IsDebuggingEnabled IsDebuggingEnabled IsDebuggingEnabled IsDebuggingEnabled

Gets a value indicating whether the current HTTP request is in debug mode.

IsPostNotification IsPostNotification IsPostNotification IsPostNotification

Gets a value that is the current processing point in the ASP.NET pipeline just after an HttpApplication event has finished processing.

IsWebSocketRequest IsWebSocketRequest IsWebSocketRequest IsWebSocketRequest

Gets a value that indicates whether the request is an AspNetWebSocket request.

IsWebSocketRequestUpgrading IsWebSocketRequestUpgrading IsWebSocketRequestUpgrading IsWebSocketRequestUpgrading

Gets a value that indicates whether the connection is upgrading from an HTTP connection to an AspNetWebSocket connection.

Items Items Items Items

Gets a key/value collection that can be used to organize and share data between an IHttpModule interface and an IHttpHandler interface during an HTTP request.

PageInstrumentation PageInstrumentation PageInstrumentation PageInstrumentation

Gets a reference to the page-instrumentation service instance for this request.

PreviousHandler PreviousHandler PreviousHandler PreviousHandler

Gets the IHttpHandler object for the parent handler.

Profile Profile Profile Profile

Gets the ProfileBase object for the current user profile.

Request Request Request Request

Gets the HttpRequest object for the current HTTP request.

Response Response Response Response

Gets the HttpResponse object for the current HTTP response.

Server Server Server Server

Gets the HttpServerUtility object that provides methods used in processing Web requests.

Session Session Session Session

Gets the HttpSessionState object for the current HTTP request.

SkipAuthorization SkipAuthorization SkipAuthorization SkipAuthorization

Gets or sets a value that specifies whether the UrlAuthorizationModule object should skip the authorization check for the current request.

ThreadAbortOnTimeout ThreadAbortOnTimeout ThreadAbortOnTimeout ThreadAbortOnTimeout

Gets or sets a value that specifies whether the ASP.NET runtime should call Abort() on the thread that is servicing this request when the request times out.

Timestamp Timestamp Timestamp Timestamp

Gets the initial timestamp of the current HTTP request.

Trace Trace Trace Trace

Gets the TraceContext object for the current HTTP response.

User User User User

Gets or sets security information for the current HTTP request.

WebSocketNegotiatedProtocol WebSocketNegotiatedProtocol WebSocketNegotiatedProtocol WebSocketNegotiatedProtocol

Gets the negotiated protocol that was sent from the server to the client for an AspNetWebSocket connection.

WebSocketRequestedProtocols WebSocketRequestedProtocols WebSocketRequestedProtocols WebSocketRequestedProtocols

Gets the ordered list of protocols requested by the client.

Methods

AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>) AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>) AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>) AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>)

Accepts an AspNetWebSocket request using the specified user function.

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

Accepts an AspNetWebSocket request using the specified user function and options object.

AddError(Exception) AddError(Exception) AddError(Exception) AddError(Exception)

Adds an exception to the exception collection for the current HTTP request.

AddOnRequestCompleted(Action<HttpContext>) AddOnRequestCompleted(Action<HttpContext>) AddOnRequestCompleted(Action<HttpContext>) AddOnRequestCompleted(Action<HttpContext>)

Raises a virtual event that occurs when the HTTP part of the request is ending.

ClearError() ClearError() ClearError() ClearError()

Clears all errors for the current HTTP request.

DisposeOnPipelineCompleted(IDisposable) DisposeOnPipelineCompleted(IDisposable) DisposeOnPipelineCompleted(IDisposable) DisposeOnPipelineCompleted(IDisposable)

Enables an object's Dispose() method to be called when the AspNetWebSocket connection part of this request is completed.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetAppConfig(String) GetAppConfig(String) GetAppConfig(String) GetAppConfig(String)

Returns requested configuration information for the current application.

GetConfig(String) GetConfig(String) GetConfig(String) GetConfig(String)

Returns requested configuration information for the current HTTP request.

GetGlobalResourceObject(String, String) GetGlobalResourceObject(String, String) GetGlobalResourceObject(String, String) GetGlobalResourceObject(String, String)

Gets an application-level resource object based on the specified ClassKey and ResourceKey properties.

GetGlobalResourceObject(String, String, CultureInfo) GetGlobalResourceObject(String, String, CultureInfo) GetGlobalResourceObject(String, String, CultureInfo) GetGlobalResourceObject(String, String, CultureInfo)

Gets an application-level resource object based on the specified ClassKey and ResourceKey properties, and on the CultureInfo object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLocalResourceObject(String, String) GetLocalResourceObject(String, String) GetLocalResourceObject(String, String) GetLocalResourceObject(String, String)

Gets a page-level resource object based on the specified VirtualPath and ResourceKey properties.

GetLocalResourceObject(String, String, CultureInfo) GetLocalResourceObject(String, String, CultureInfo) GetLocalResourceObject(String, String, CultureInfo) GetLocalResourceObject(String, String, CultureInfo)

Gets a page-level resource object based on the specified VirtualPath and ResourceKey properties, and on the CultureInfo object.

GetSection(String) GetSection(String) GetSection(String) GetSection(String)

Gets a specified configuration section for the current application's default configuration.

GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
RemapHandler(IHttpHandler) RemapHandler(IHttpHandler) RemapHandler(IHttpHandler) RemapHandler(IHttpHandler)

Enables you to specify a handler for the request.

RewritePath(String) RewritePath(String) RewritePath(String) RewritePath(String)

Rewrites the URL using the given path.

RewritePath(String, Boolean) RewritePath(String, Boolean) RewritePath(String, Boolean) RewritePath(String, Boolean)

Rewrites the URL using the given path and a Boolean value that specifies whether the virtual path for server resources is modified.

RewritePath(String, String, String) RewritePath(String, String, String) RewritePath(String, String, String) RewritePath(String, String, String)

Rewrites the URL by using the given path, path information, and query string information.

RewritePath(String, String, String, Boolean) RewritePath(String, String, String, Boolean) RewritePath(String, String, String, Boolean) RewritePath(String, String, String, Boolean)

Rewrites the URL using the given virtual path, path information, query string information, and a Boolean value that specifies whether the client file path is set to the rewrite path.

SetSessionStateBehavior(SessionStateBehavior) SetSessionStateBehavior(SessionStateBehavior) SetSessionStateBehavior(SessionStateBehavior) SetSessionStateBehavior(SessionStateBehavior)

Sets the type of session state behavior that is required in order to support an HTTP request.

ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

IServiceProvider.GetService(Type) IServiceProvider.GetService(Type) IServiceProvider.GetService(Type) IServiceProvider.GetService(Type)

Returns an object for the current service type.

Applies to

See Also