HttpContext 类

定义

封装有关个别 HTTP 请求的所有 HTTP 特定的信息。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
继承
HttpContext
实现

示例

下面的示例演示如何访问和显示 HttpContext 对象的属性。The following example demonstrates how to access and display properties of the HttpContext object. 使用 Page 对象的 Context 属性访问当前 HTTP 请求的上下文。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>

注解

继承 IHttpModuleIHttpHandler 接口的类将为当前 HTTP 请求的 HttpContext 对象提供引用。Classes that inherit the IHttpModule and IHttpHandler interfaces are provided a reference to an HttpContext object for the current HTTP request. 对象提供对请求的内部 RequestResponseServer 属性的访问。The object provides access to the intrinsic Request, Response, and Server properties for the request.

重要

HttpRequest 完成时,此对象可用于垃圾回收。This object is ready for garbage collection when the HttpRequest is completed. 请求完成后,其使用可能导致未定义的行为,如 NullReferenceExceptionIts usage after the request completes could lead to undefined behavior, such as a NullReferenceException.

此对象仅在由 ASP.NET 控制的线程中可用。This object is only available in the thread controlled by ASP.NET. 后台线程中的使用情况可能导致未定义的行为。Usage in background threads could lead to undefined behavior.

构造函数

HttpContext(HttpRequest, HttpResponse)

使用指定的请求和响应对象初始化 HttpContext 类的新实例。Initializes a new instance of the HttpContext class by using the specified request and response objects.

HttpContext(HttpWorkerRequest)

使用指定的辅助请求对象初始化 HttpContext 类的新实例。Initializes a new instance of the HttpContext class that uses the specified worker-request object.

属性

AllErrors

获取在处理 HTTP 请求的过程中累积的错误数组。Gets an array of errors accumulated while processing an HTTP request.

AllowAsyncDuringSyncStages

获取或设置一个值,此值指示 ASP.NET 请求处理过程中是否允许非预期的异步操作。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

为当前 HTTP 请求获取 HttpApplicationState 对象。Gets the HttpApplicationState object for the current HTTP request.

ApplicationInstance

为当前 HTTP 请求获取或设置 HttpApplication 对象。Gets or sets the HttpApplication object for the current HTTP request.

AsyncPreloadMode

获取或设置包含适用于异步预加载模式的标志的对象。Gets or sets an object that contains flags that pertain to asynchronous preload mode.

Cache

获取当前应用程序域的 Cache 对象。Gets the Cache object for the current application domain.

Current

为当前 HTTP 请求获取或设置 HttpContext 对象。Gets or sets the HttpContext object for the current HTTP request.

CurrentHandler

获取表示当前正在执行的处理程序的 IHttpHandler 对象。Gets the IHttpHandler object that represents the currently executing handler.

CurrentNotification

获取一个 RequestNotification 值,该值指示当前正在处理的 HttpApplication 事件。Gets a RequestNotification value that indicates the current HttpApplication event that is processing.

Error

获取在处理 HTTP 请求的过程中累积的第一个错误(如果有)。Gets the first error (if any) accumulated during HTTP request processing.

Handler

获取或设置负责处理 HTTP 请求的 IHttpHandler 对象。Gets or sets the IHttpHandler object responsible for processing the HTTP request.

IsCustomErrorEnabled

获取一个值,该值指示是否已为当前 HTTP 请求启用自定义错误。Gets a value indicating whether custom errors are enabled for the current HTTP request.

IsDebuggingEnabled

获取一个值,该值指示当前 HTTP 请求是否处于调试模式。Gets a value indicating whether the current HTTP request is in debug mode.

IsPostNotification

HttpApplication 事件完成处理之后获取 ASP.NET 管道的当前进程点的值。Gets a value that is the current processing point in the ASP.NET pipeline just after an HttpApplication event has finished processing.

IsWebSocketRequest

获取一个值,该值指示此请求是否是一个 AspNetWebSocket 请求。Gets a value that indicates whether the request is an AspNetWebSocket request.

IsWebSocketRequestUpgrading

获取指示连接是否从 HTTP 连接升级到 AspNetWebSocket 连接的值。Gets a value that indicates whether the connection is upgrading from an HTTP connection to an AspNetWebSocket connection.

Items

获取可用于在 HTTP 请求过程中在 IHttpModule 接口和 IHttpHandler 接口之间组织和共享数据的键/值集合。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

获取此要求的页检测服务实例的引用。Gets a reference to the page-instrumentation service instance for this request.

PreviousHandler

获取父处理程序的 IHttpHandler 对象。Gets the IHttpHandler object for the parent handler.

Profile

获取当前用户配置文件的 ProfileBase 对象。Gets the ProfileBase object for the current user profile.

Request

为当前 HTTP 请求获取 HttpRequest 对象。Gets the HttpRequest object for the current HTTP request.

Response

获取当前 HTTP 响应的 HttpResponse 对象。Gets the HttpResponse object for the current HTTP response.

Server

获取提供用于处理 Web 请求的方法的 HttpServerUtility 对象。Gets the HttpServerUtility object that provides methods used in processing Web requests.

Session

为当前 HTTP 请求获取 HttpSessionState 对象。Gets the HttpSessionState object for the current HTTP request.

SkipAuthorization

获取或设置一个值,该值指定 UrlAuthorizationModule 对象是否应跳过对当前请求的授权检查。Gets or sets a value that specifies whether the UrlAuthorizationModule object should skip the authorization check for the current request.

ThreadAbortOnTimeout

获取或设置一个值,此值指示 ASP.NET 运行时是否应在请求超时时,调用为该请求提供服务的线程上的 Abort()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

获取当前 HTTP 请求的初始时间戳。Gets the initial timestamp of the current HTTP request.

Trace

获取当前 HTTP 响应的 TraceContext 对象。Gets the TraceContext object for the current HTTP response.

User

为当前 HTTP 请求获取或设置安全信息。Gets or sets security information for the current HTTP request.

WebSocketNegotiatedProtocol

获取用于 AspNetWebSocket 连接而从服务器发送到客户端的协商协议。Gets the negotiated protocol that was sent from the server to the client for an AspNetWebSocket connection.

WebSocketRequestedProtocols

获取客户要求的子协议列表的有序列表。Gets the ordered list of protocols requested by the client.

方法

AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>)

接受一个使用指定用户函数的 AspNetWebSocket 请求。Accepts an AspNetWebSocket request using the specified user function.

AcceptWebSocketRequest(Func<AspNetWebSocketContext,Task>, AspNetWebSocketOptions)

接受一个使用指定的用户函数和选项对象 AspNetWebSocket 请求。Accepts an AspNetWebSocket request using the specified user function and options object.

AddError(Exception)

将异常添加到当前 HTTP 请求的异常集合中。Adds an exception to the exception collection for the current HTTP request.

AddOnRequestCompleted(Action<HttpContext>)

引发在请求的 HTTP 部分结束时发生的虚拟事件。Raises a virtual event that occurs when the HTTP part of the request is ending.

ClearError()

清除当前 HTTP 请求的所有错误。Clears all errors for the current HTTP request.

DisposeOnPipelineCompleted(IDisposable)

启动一个对象 Dispose() 方法的调用,当此请求 AspNetWebSocket 的连接部分完成时。Enables an object's Dispose() method to be called when the AspNetWebSocket connection part of this request is completed.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetAppConfig(String)

为当前应用程序返回请求的配置信息。Returns requested configuration information for the current application.

GetConfig(String)

为当前 HTTP 请求返回所请求的配置信息。Returns requested configuration information for the current HTTP request.

GetGlobalResourceObject(String, String)

根据指定的 ClassKeyResourceKey 属性,获取应用程序级别资源对象。Gets an application-level resource object based on the specified ClassKey and ResourceKey properties.

GetGlobalResourceObject(String, String, CultureInfo)

根据指定的 ClassKeyResourceKey 属性以及 CultureInfo 对象,获取一个应用程序级别资源对象。Gets an application-level resource object based on the specified ClassKey and ResourceKey properties, and on the CultureInfo object.

GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLocalResourceObject(String, String)

根据指定的 VirtualPathResourceKey 属性,获取页级别资源对象。Gets a page-level resource object based on the specified VirtualPath and ResourceKey properties.

GetLocalResourceObject(String, String, CultureInfo)

根据指定的 VirtualPathResourceKey 属性以及 CultureInfo 对象,获取一个页级别资源对象。Gets a page-level resource object based on the specified VirtualPath and ResourceKey properties, and on the CultureInfo object.

GetSection(String)

获取当前应用程序的默认配置的指定配置节。Gets a specified configuration section for the current application's default configuration.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
RemapHandler(IHttpHandler)

用于为请求指定处理程序。Enables you to specify a handler for the request.

RewritePath(String)

使用给定路径重写 URL。Rewrites the URL using the given path.

RewritePath(String, Boolean)

使用给定路径和一个布尔值重写 URL,该布尔值用于指定是否修改服务器资源的虚拟路径。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)

使用给定的路径、路径信息和查询字符串信息重写 URL。Rewrites the URL by using the given path, path information, and query string information.

RewritePath(String, String, String, Boolean)

使用给定虚拟路径、路径信息、查询字符串信息和一个布尔值重写 URL,该布尔值用于指定是否将客户端文件路径设置为重写路径。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)

设置支持 HTTP 请求所需的会话状态行为的类型。Sets the type of session state behavior that is required in order to support an HTTP request.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

显式界面实现

IServiceProvider.GetService(Type)

返回当前服务类型的对象。Returns an object for the current service type.

适用于

另请参阅