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. 目前 HTTP 要求的內容是使用 Page 物件的 Context 屬性來存取。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

取得 HttpServerUtility 物件,這個物件提供用於處理 Web 要求的方法。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)

加入例外狀況 (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 的淺層複本 (Shallow Copy)。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.

適用於

另請參閱