HttpContext HttpContext HttpContext HttpContext Class

定義

封裝所有關於個別 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
繼承
HttpContextHttpContextHttpContextHttpContext
實作

範例

下列範例示範如何存取及顯示的屬性HttpContext物件。The following example demonstrates how to access and display properties of the HttpContext object. 目前 HTTP 要求的內容會使用來存取Context屬性Page物件。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介面所提供的參考HttpContext目前 HTTP 要求的物件。Classes that inherit the IHttpModule and IHttpHandler interfaces are provided a reference to an HttpContext object for the current HTTP request. 物件提供內建函式的存取RequestResponse,和Server要求屬性。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(HttpRequest, HttpResponse) HttpContext(HttpRequest, HttpResponse) HttpContext(HttpRequest, HttpResponse)

使用指定的要求和回應物件,初始化 HttpContext 類別的新執行個體。Initializes a new instance of the HttpContext class by using the specified request and response objects.

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

初始化 HttpContext 類別 (使用指定的背景工作要求物件) 的新執行個體。Initializes a new instance of the HttpContext class that uses the specified worker-request object.

屬性

AllErrors AllErrors AllErrors AllErrors

取得處理 HTTP 要求時的錯誤累積陣列。Gets an array of errors accumulated while processing an HTTP request.

AllowAsyncDuringSyncStages AllowAsyncDuringSyncStages AllowAsyncDuringSyncStages 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 Application Application Application

取得目前 HTTP 要求的 HttpApplicationState 物件。Gets the HttpApplicationState object for the current HTTP request.

ApplicationInstance ApplicationInstance ApplicationInstance ApplicationInstance

取得或設定目前 HTTP 要求的 HttpApplication 物件。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

取得目前應用程式定義域的 Cache 物件。Gets the Cache object for the current application domain.

Current Current Current Current

取得或設定目前 HTTP 要求的 HttpContext 物件。Gets or sets the HttpContext object for the current HTTP request.

CurrentHandler CurrentHandler CurrentHandler CurrentHandler

取得表示目前正在執行處理常式的 IHttpHandler 物件。Gets the IHttpHandler object that represents the currently executing handler.

CurrentNotification CurrentNotification CurrentNotification CurrentNotification

取得 RequestNotification 值,表示目前正在處理的 HttpApplication 事件。Gets a RequestNotification value that indicates the current HttpApplication event that is processing.

Error Error Error Error

取得在 HTTP 要求處理期間累積的第一個錯誤 (若有的話)。Gets the first error (if any) accumulated during HTTP request processing.

Handler Handler Handler Handler

取得或設定負責處理 HTTP 要求的 IHttpHandler 物件。Gets or sets the IHttpHandler object responsible for processing the HTTP request.

IsCustomErrorEnabled IsCustomErrorEnabled IsCustomErrorEnabled IsCustomErrorEnabled

取得值,指出是否對目前 HTTP 要求啟用自訂錯誤。Gets a value indicating whether custom errors are enabled for the current HTTP request.

IsDebuggingEnabled IsDebuggingEnabled IsDebuggingEnabled IsDebuggingEnabled

取得值,指出目前 HTTP 要求是否處於偵錯模式。Gets a value indicating whether the current HTTP request is in debug mode.

IsPostNotification IsPostNotification IsPostNotification 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 IsWebSocketRequest IsWebSocketRequest IsWebSocketRequest

取得值,指出要求是否為 AspNetWebSocket 要求。Gets a value that indicates whether the request is an AspNetWebSocket request.

IsWebSocketRequestUpgrading IsWebSocketRequestUpgrading IsWebSocketRequestUpgrading IsWebSocketRequestUpgrading

取得值,指出連線是否從 HTTP 連線升級至 AspNetWebSocket 連線。Gets a value that indicates whether the connection is upgrading from an HTTP connection to an AspNetWebSocket connection.

Items Items Items 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 PageInstrumentation PageInstrumentation PageInstrumentation

針對此要求,取得頁面檢測服務執行個體的參考。Gets a reference to the page-instrumentation service instance for this request.

PreviousHandler PreviousHandler PreviousHandler PreviousHandler

取得父處理常式的 IHttpHandler 物件。Gets the IHttpHandler object for the parent handler.

Profile Profile Profile Profile

取得目前使用者設定檔的 ProfileBase 物件。Gets the ProfileBase object for the current user profile.

Request Request Request Request

取得目前 HTTP 要求的 HttpRequest 物件。Gets the HttpRequest object for the current HTTP request.

Response Response Response Response

取得目前 HTTP 回應的 HttpResponse 物件。Gets the HttpResponse object for the current HTTP response.

Server Server Server Server

取得 HttpServerUtility 物件,其提供用以處理 Web 要求的方法。Gets the HttpServerUtility object that provides methods used in processing Web requests.

Session Session Session Session

取得目前 HTTP 要求的 HttpSessionState 物件。Gets the HttpSessionState object for the current HTTP request.

SkipAuthorization SkipAuthorization SkipAuthorization SkipAuthorization

取得或設定數值,指定 UrlAuthorizationModule 物件是否應對目前要求略過授權檢查。Gets or sets a value that specifies whether the UrlAuthorizationModule object should skip the authorization check for the current request.

ThreadAbortOnTimeout ThreadAbortOnTimeout ThreadAbortOnTimeout 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 Timestamp Timestamp Timestamp

取得目前 HTTP 要求的初始時間戳記。Gets the initial timestamp of the current HTTP request.

Trace Trace Trace Trace

取得目前 HTTP 回應的 TraceContext 物件。Gets the TraceContext object for the current HTTP response.

User User User User

取得或設定目前 HTTP 要求的安全性資訊。Gets or sets security information for the current HTTP request.

WebSocketNegotiatedProtocol WebSocketNegotiatedProtocol WebSocketNegotiatedProtocol WebSocketNegotiatedProtocol

取得伺服器針對 AspNetWebSocket 連線傳送至用戶端的交涉通訊協定。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.

方法

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

接受使用指定之使用者函式的 AspNetWebSocket 要求。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)

接受使用指定之使用者函式及選項物件的 AspNetWebSocket 要求。Accepts an AspNetWebSocket request using the specified user function and options object.

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

加入例外狀況 (Exception) 至目前 HTTP 要求的例外狀況集合。Adds an exception to the exception collection for the current HTTP request.

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

引發虛擬事件,該事件會在要求的 HTTP 部分結束時發生。Raises a virtual event that occurs when the HTTP part of the request is ending.

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

清除目前 HTTP 要求的所有錯誤。Clears all errors for the current HTTP request.

DisposeOnPipelineCompleted(IDisposable) DisposeOnPipelineCompleted(IDisposable) DisposeOnPipelineCompleted(IDisposable) 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) 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)

傳回目前 HTTP 要求的要求組態資訊。Returns requested configuration information for the current HTTP request.

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

根據指定的 ClassKeyResourceKey 屬性,取得應用程式層級資源物件。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)

根據指定的 ClassKeyResourceKey 屬性及 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)

根據指定的 VirtualPathResourceKey 屬性,取得頁面層級資源物件。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)

根據指定的 VirtualPathResourceKey 屬性及 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()

取得目前執行個體的 TypeGets the Type of the current instance.

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

建立目前 Object 的淺層複製。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)

使用指定的路徑重寫 URL。Rewrites the URL using the given path.

RewritePath(String, Boolean) RewritePath(String, Boolean) RewritePath(String, Boolean) 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) RewritePath(String, String, String) RewritePath(String, String, String) RewritePath(String, String, String)

使用指定的路徑、路徑資訊和查詢字串資訊重新寫入 URL。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)

使用指定的虛擬路徑、路徑資訊、查詢字串資訊和布林值重寫 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) SetSessionStateBehavior(SessionStateBehavior) SetSessionStateBehavior(SessionStateBehavior) SetSessionStateBehavior(SessionStateBehavior)

設定支援 HTTP 要求所需之工作階段狀態行為的類型。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)

明確介面實作

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

傳回目前服務類型的物件。Returns an object for the current service type.

適用於

另請參閱