Поделиться через


Метод IGlobalTraceEventProvider::GetCurrentHttpRequestContext

Извлекает контекст HTTP для событий трассировки, относящихся к запросу.

Синтаксис

virtual HRESULT GetCurrentHttpRequestContext(  
   IHttpContext** ppHttpContext  
) = 0;  

Параметры

ppHttpContext
Указатель на адрес IHttpContext интерфейса; в противном случае — значение NULL.

Возвращаемое значение

Объект HRESULT. Допустимые значения включают, но не ограничиваются, значения, приведенные в следующей таблице.

Значение Определение
S_OK Указывает, что операция прошла успешно.
ERROR_NOT_SUPPORTED Указывает, что метод не поддерживается.

Комментарии

Производные классы CGlobalModule, которые регистрируются для GL_TRACE_EVENT типов событий, получают указатель IGlobalTraceEventProvider в качестве параметра в чистом методе CGlobalModule::OnGlobalTraceEventvirtual. Затем можно получить указатель IHttpContext , вызвав GetCurrentHttpRequestContext метод для этого указателя IGlobalTraceEventProvider .

Одним из возможных вариантов использования является GetCurrentHttpRequestContext предоставление настраиваемой буферизации событий.

GetCurrentHttpRequestContext поведение зависит от реализации. В качестве руководства следует использовать следующие сведения, но они могут быть неправильными во всех сценариях:

  • Классы, предоставляющие события трассировки HTTP, объявляют переменную-член private``IHttpContext указателя. Эта переменная инициализируется во время построения допустимым IHttpContext указателем. При вызове GetCurrentHttpRequestContextдля параметра разыменования ppHttpContext устанавливается эта переменная и возвращается S_OK.

  • Классы, предоставляющие глобальные события трассировки, не изменяют ppHttpContext параметр и возвращают ERROR_NOT_SUPPORTED немедленно.

Примечания для разработчиков

IGlobalTraceEventProvider разработчики отвечают за управление памятью с помощью этих данных; Поэтому разработчики, использующие динамическое выделение памяти, IGlobalTraceEventProvider должны освободить или вызвать deleteIHttpContext указатель, когда он больше не нужен.

Примечания для абонентов

IGlobalTraceEventProvider разработчики отвечают за управление памятью с помощью этих данных; IGlobalTraceEventProvider поэтому клиенты не должны освобождать или вызывать delete возвращаемый IHttpContext указатель, если эти данные больше не нужны.

Пример

В следующем примере кода показано, как создать глобальный модуль, который прослушивает события GL_TRACE_EVENT , а также объявляет и инициализирует структуру HTTP_TRACE_CONFIGURATION , которая фильтрует события. Затем модуль получает указатель путем IHttpContext вызова GetCurrentHttpRequestContext метода .

#pragma warning( disable : 4290 )
#pragma warning( disable : 4530 )

#define _WINSOCKAPI_
#include <windows.h>
#include <sal.h>
#include <tchar.h>
#include <initguid.h>
#include <httptrace.h>
#include <httpserv.h>
#include <httpcach.h>

// The CGlobalTraceModule class creates the CGlobalModule 
// class and registers for GL_TRACE_EVENT events.
class CGlobalContainerModule : public CGlobalModule
{
public:
    // Creates the destructor for the 
    // CGlobalTraceModule class.
    virtual ~CGlobalContainerModule()
    {

    }

    // The RegisterGlobalModule method creates and registers 
    // a new CGlobalTraceModule for GL_TRACE_EVENT events.
    // dwServerVersion: the current server version.
    // pModuleInfo: the current IHttpModuleRegistrationInfo pointer.
    // pGlobalInfo: the current IHttpServer pointer.
    // return: ERROR_NOT_ENOUGH_MEMORY if the heap is out of 
    // memory; otherwise, the value from the call to the 
    // SetGlobalNotifications method on the pModuleInfo pointer.
    static HRESULT RegisterGlobalModule
    (
        DWORD dwServerVersion,
        IHttpModuleRegistrationInfo* pModuleInfo,
        IHttpServer* pGlobalInfo
    )
    {        
        // The IHttpModuleRegistrationInfo 
        // pointermust not be NULL.
        if (NULL == pModuleInfo)
        {
            return E_INVALIDARG;
        }

        // Get the HTTP_MODULE_ID from the 
        // IHttpModuleRegistrationInfo pointer.
        HTTP_MODULE_ID moduleId = 
            pModuleInfo->GetId();

        // The HTTP_MODULE_ID pointer 
        // must not be NULL.
        if (NULL == moduleId)
        {
            return E_INVALIDARG;
        }

        // Create a new CGlobalContainerModule pointer
        // using the HTTP_MODULE_ID from the 
        // IHttpModuleRegistrationInfo pointer.
        CGlobalContainerModule* containerModule = 
            new CGlobalContainerModule(moduleId);

        // Return an out-of-memory error if the containerModule 
        // is NULL after the call to the new operator.
        if (NULL == containerModule)
        {            
            return HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
        }                                          

        // Attempt to set global notification 
        // for an GL_TRACE_EVENT event by using 
        // the traceModule as a listener.
        HRESULT hr = pModuleInfo->SetGlobalNotifications
            (containerModule, GL_TRACE_EVENT);

        // Return the HRESULT from the call to 
        // the SetGlobalNotifications method.        
        return hr;
    }

    // The OnGlobalTraceEvent method is the callback
    // method for GL_TRACE_EVENT events in the pipeline.
    // pProvider: the IGlobalTraceEventProvider pointer.
    // return: GL_NOTIFICATION_CONTINUE.
    virtual 
    GLOBAL_NOTIFICATION_STATUS
    OnGlobalTraceEvent
    (
        IN IGlobalTraceEventProvider* pProvider
    )
    {
        // If the IGlobalTraceEventProvider pointer 
        // is NULL, return GL_NOTIFICATION_CONTINUE.
        if (NULL == pProvider)
        {
            return GL_NOTIFICATION_CONTINUE;
        }

        // Declare an IHttpContext pointer.
        IHttpContext* httpContext = NULL;

        // Declare an HRESULT and initialize
        // the HRESULT to E_FAIL.
        HRESULT hr = E_FAIL;

        // Call the GetCurrentHttpRequestContext
        // method on the IGlobalTraceEventProvider
        // pointer.
        hr = pProvider->GetCurrentHttpRequestContext(&httpContext);

        // Return GL_NOTIFICATION_CONTINUE.
        return GL_NOTIFICATION_CONTINUE;
    }

    // The Terminate method is required for
    // non-abstract CGlobalTraceModule classes.
    // This method calls delete on this.
    virtual VOID Terminate(VOID)
    {
        delete this;
    }
    // Creates the constructor for the CGlobalTraceModule 
    // class. This constructor initializes the CEventWriter
    // to write to the application event log.
    // moduleId: the current module identifier.
    CGlobalContainerModule(HTTP_MODULE_ID moduleId)        
    {
        m_moduleId = moduleId;
    }
private:
    // Specify the HTTP_MODULE_ID
    // for this module.
    HTTP_MODULE_ID m_moduleId;
};

// The RegisterModule method is the 
// main entry point for the DLL.
// dwServerVersion: the current server version.
// pModuleInfo: the current 
// IHttpModuleRegistrationInfo pointer.
// pGlobalInfo: the current IHttpServer pointer.
// return: the value returned by calling the
// CGlobalContainerModule::RegisterGlobalModule
// method.
HRESULT
__stdcall
RegisterModule(
    DWORD dwServerVersion,
    IHttpModuleRegistrationInfo* pModuleInfo,
    IHttpServer* pGlobalInfo
)
{        
    // Call the static method for initialization.
    return CGlobalContainerModule::RegisterGlobalModule            
        (dwServerVersion, 
         pModuleInfo, 
         pGlobalInfo);             
}

Модуль должен экспортировать функцию RegisterModule . Эту функцию можно экспортировать, создав файл определения модуля (DEF- файл) для проекта, или скомпилировать модуль с помощью /EXPORT:RegisterModule параметра . Дополнительные сведения см. в разделе Пошаговое руководство. Создание модуля HTTP Request-Level с помощью машинного кода.

При необходимости можно скомпилировать код с помощью __stdcall (/Gz) соглашения о вызовах вместо явного объявления соглашения о вызовах для каждой функции.

Требования

Тип Описание
клиент — IIS 7.0 в Windows Vista
— IIS 7.5 в Windows 7
— IIS 8.0 в Windows 8
— IIS 10.0 в Windows 10
Сервер — IIS 7.0 в Windows Server 2008
— IIS 7.5 в Windows Server 2008 R2
— IIS 8.0 в Windows Server 2012
— IIS 8.5 в Windows Server 2012 R2
— IIS 10.0 в Windows Server 2016
Продукт — IIS 7.0, IIS 7.5, IIS 8.0, IIS 8.5, IIS 10.0
- IIS Express 7.5, IIS Express 8.0, IIS Express 10.0
Заголовок Httpserv.h

См. также:

Интерфейс IGlobalTraceEventProvider