HttpContext Класс
Определение
Инкапсулирует все связанные с НТТР сведения об отдельном НТТР-запросе.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-запроса осуществляется с помощью свойства 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>
Комментарии
Классы, наследующие интерфейсы IHttpModule и IHttpHandler, предоставляются ссылкой на объект HttpContext для текущего HTTP-запроса.Classes that inherit the IHttpModule and IHttpHandler interfaces are provided a reference to an HttpContext object for the current HTTP request. Объект предоставляет доступ к внутренним свойствам Request, Responseи 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. Его использование после завершения запроса может привести к неопределенному поведению, например NullReferenceException.Its 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 |
Возвращает объект HttpApplicationState для текущего HTTP-запроса.Gets the HttpApplicationState object for the current HTTP request. |
ApplicationInstance |
Возвращает или задает объект HttpApplication для текущего HTTP-запроса.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 |
Возвращает или задает объект HttpContext для текущего HTTP-запроса.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 |
Возвращает первую ошибку (при наличии таковой), возникшую в ходе обработки НТТР-запроса.Gets the first error (if any) accumulated during HTTP request processing. |
Handler |
Возвращает или задает объект IHttpHandler, отвечающий за обработку HTTP-запроса.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 |
Получает значение, которое является текущей точкой обработки в конвейере ASP.NET сразу после завершения обработки события HttpApplication.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 |
Получает коллекцию значений и ключей, которая может быть использована для систематизации и обмена данными между интерфейсами IHttpModule и IHttpHandler во время прохождения HTTP-запроса.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 |
Возвращает объект HttpRequest для текущего HTTP-запроса.Gets the HttpRequest object for the current HTTP request. |
Response |
Возвращает объект HttpResponse для текущего HTTP-ответа.Gets the HttpResponse object for the current HTTP response. |
Server |
Получает объект HttpServerUtility, предоставляющий методы, используемые при обработке веб-запросов.Gets the HttpServerUtility object that provides methods used in processing Web requests. |
Session |
Возвращает объект HttpSessionState для текущего HTTP-запроса.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 |
Возвращает объект TraceContext для текущего HTTP-ответа.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) |
Получает объект ресурса на уровне приложения на основе указанных свойств ClassKey и ResourceKey.Gets an application-level resource object based on the specified ClassKey and ResourceKey properties. |
GetGlobalResourceObject(String, String, CultureInfo) |
Получает объект ресурса на уровне приложения на основе заданных свойств ClassKey и ResourceKey и в объекте 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) |
Получает объект ресурса на уровне станицы на основе заданных свойств VirtualPath и ResourceKey.Gets a page-level resource object based on the specified VirtualPath and ResourceKey properties. |
GetLocalResourceObject(String, String, CultureInfo) |
Получает объект ресурса на уровне страницы на основе заданных свойств VirtualPath и ResourceKey, а также в объекте 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() |
Возвращает объект Type для текущего экземпляра.Gets 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. |