다음을 통해 공유


CHttpModule::OnAsyncCompletion 메서드

비동기 작업이 처리를 완료한 후에 발생하는 비동기 완료 이벤트를 처리할 메서드를 나타냅니다.

구문

virtual REQUEST_NOTIFICATION_STATUS OnAsyncCompletion(  
   IN IHttpContext* pHttpContext,  
   IN DWORD dwNotification,  
   IN BOOL fPostNotification,  
   IN OUT IHttpEventProvider* pProvider,  
   IN IHttpCompletionInfo* pCompletionInfo  
);  

매개 변수

pHttpContext
[IN] IHttpContext 인터페이스에 대한 포인터입니다 .

dwNotification
[IN] DWORD 관련 알림에 대한 비트 마스크를 포함하는 값입니다.

fPostNotification
[IN] true 는 사후 이벤트에 대한 알림임을 나타내기 위한 것입니다. 그렇지 않으면 입니다 false.

pProvider
[IN] IHttpEventProvider 인터페이스에 대한 포인터입니다.

pCompletionInfo
[IN] IHttpCompletionInfo 인터페이스에 대한 포인터입니다.

반환 값

REQUEST_NOTIFICATION_STATUS 값입니다.

설명

특정 알림을 등록하여 호출되는 다른 많은 CHttpModule 메서드와 달리 IIS는 비동기 작업이 완료된 경우에만 모듈의 OnAsyncCompletion 메서드를 호출합니다. 예를 들어 요청 수준 모듈이 IHttpResponse::WriteEntityChunks 메서드를 호출하고 비동기 완료를 지정하는 경우 IIS는 작업이 완료되면 모듈의 OnAsyncCompletion 메서드를 호출합니다.

IIS는 메서드를 OnAsyncCompletion 호출할 때 매개 변수에 dwNotification 알림 유형을 지정하고 매개 변수를 사용하여 fPostNotification 이벤트 또는 사후 이벤트에 대한 알림인지 여부를 나타냅니다. 또한 IIS는 매개 변수가 IHttpCompletionInfo 가리키는 인터페이스를 pCompletionInfo 제공합니다. 이 인터페이스를 사용하여 비동기 완료에 대한 추가 정보를 검색할 수 있습니다.

예제

다음 코드 예제에서는 다음 작업을 수행하는 HTTP 모듈을 만드는 방법을 보여 줍니다.

  1. 모듈은 RQ_BEGIN_REQUESTRQ_MAP_REQUEST_HANDLER 알림을 등록합니다.

  2. 모듈은 OnBeginRequest, OnMapRequestHandlerOnAsyncCompletion 메서드를 포함하는 클래스를 만듭니다CHttpModule.

  3. 웹 클라이언트가 URL을 요청하면 IIS는 모듈의 OnBeginRequest 메서드를 호출합니다. 이 메서드는 다음 작업을 수행합니다.

    1. 기존 응답 버퍼를 지우고 응답에 대한 MIME 형식을 설정합니다.

    2. 예제 문자열을 만들고 웹 클라이언트에 비동기적으로 반환합니다.

    3. 오류 또는 비동기 완료를 테스트합니다. 비동기 완료가 보류 중인 경우 모듈은 보류 중인 알림 상태 통합 요청 처리 파이프라인에 반환합니다.

  4. IIS는 모듈의 메서드를 OnMapRequestHandler 호출합니다. 이 메서드는 다음 작업을 수행합니다.

    1. 현재 응답 버퍼를 웹 클라이언트로 플러시합니다.

    2. 오류 또는 비동기 완료를 테스트합니다. 비동기 완료가 보류 중인 경우 모듈은 파이프라인에 보류 중인 알림 상태 반환합니다.

  5. 비동기 완료가 필요한 경우 IIS는 모듈의 OnAsyncCompletion 메서드를 호출합니다. 이 메서드는 다음 작업을 수행합니다.

    1. 유효한 IHttpCompletionInfo 인터페이스를 테스트합니다. 유효한 IHttpCompletionInfo 인터페이스가 전달된 경우 메서드는 각각 GetCompletionBytesGetCompletionStatus 메서드를 호출하여 완료된 바이트를 검색하고 비동기 작업에 대한 상태 반환합니다.

    2. 완료 정보를 포함하는 문자열을 만들고 정보를 이벤트로 이벤트 뷰어 애플리케이션 로그에 씁니다.

  6. 모듈은 메모리에서 클래스를 CHttpModule 제거한 다음 종료합니다.

#define _WINSOCKAPI_
#include <windows.h>
#include <sal.h>
#include <httpserv.h>
#include <wchar.h>

// Create the module class.
class MyHttpModule : public CHttpModule
{

public:

    REQUEST_NOTIFICATION_STATUS
    OnBeginRequest(
        IN IHttpContext * pHttpContext,
        IN IHttpEventProvider * pProvider
    )
    {
        UNREFERENCED_PARAMETER( pProvider );

        // Create an HRESULT to receive return values from methods.
        HRESULT hr;
        // Buffer to store the byte count.
        DWORD cbSent = 0;
        // Buffer to store if asyncronous completion is pending.
        BOOL fCompletionExpected = false;
        // Create an example string to return to the Web client.
        char szBuffer[] = "Hello World!";
        
        // Clear the existing response.
        pHttpContext->GetResponse()->Clear();
        // Set the MIME type to plain text.
        pHttpContext->GetResponse()->SetHeader(
            HttpHeaderContentType,"text/plain",
            (USHORT)strlen("text/plain"),TRUE);
        
        // Create a data chunk.
        HTTP_DATA_CHUNK dataChunk;
        // Set the chunk to a chunk in memory.
        dataChunk.DataChunkType = HttpDataChunkFromMemory;
        // Set the chunk to the buffer.
        dataChunk.FromMemory.pBuffer =
            (PVOID) szBuffer;
        // Set the chunk size to the buffer size.
        dataChunk.FromMemory.BufferLength =
            (USHORT) strlen(szBuffer);
        // Insert the data chunk into the response.
        hr = pHttpContext->GetResponse()->WriteEntityChunks(
            &dataChunk,1,TRUE,TRUE,&cbSent,&fCompletionExpected);

        // Test for a failure.
        if (FAILED(hr))
        {
            // Set the HTTP status.
            pHttpContext->GetResponse()->SetStatus(
                500,"Server Error",0,hr);
            // End additional processing.
            return RQ_NOTIFICATION_FINISH_REQUEST;
        }
        
        // Test for pending asynchronous operations.
        if (fCompletionExpected)
        {
            return RQ_NOTIFICATION_PENDING;
        }

        // Return processing to the pipeline.
        return RQ_NOTIFICATION_CONTINUE;
    }
    
    REQUEST_NOTIFICATION_STATUS
    OnMapRequestHandler(
        IN IHttpContext * pHttpContext,
        IN IMapHandlerProvider * pProvider
    )
    {
        // Create an HRESULT to receive return values from methods.
        HRESULT hr;
        // Buffer to store the byte count.
        DWORD cbSent = 0;
        // Buffer to store if asyncronous completion is pending.
        BOOL fCompletionExpected = false;

        // Flush the response to the client.
        hr = pHttpContext->GetResponse()->Flush(
            TRUE,FALSE,&cbSent,&fCompletionExpected);

        // Test for a failure.
        if (FAILED(hr))
        {
            // Set the HTTP status.
            pHttpContext->GetResponse()->SetStatus(
                500,"Server Error",0,hr);
        }

        // Test for pending asynchronous operations.
        if (fCompletionExpected)
        {
            return RQ_NOTIFICATION_PENDING;
        }

        // End additional processing.
        return RQ_NOTIFICATION_CONTINUE;
    }

    REQUEST_NOTIFICATION_STATUS
        OnAsyncCompletion(
        IN IHttpContext * pHttpContext,
        IN DWORD dwNotification,
        IN BOOL fPostNotification,
        IN IHttpEventProvider * pProvider,
        IN IHttpCompletionInfo * pCompletionInfo
        )
    {        
        if ( NULL != pCompletionInfo )
        {
            // Create strings for completion information.
            char szNotification[256] = "";
            char szBytes[256] = "";
            char szStatus[256] = "";

            // Retrieve and format the completion information.
            sprintf_s(szNotification,255,"Notification: %u",
                dwNotification);
            sprintf_s(szBytes,255,"Completion Bytes: %u",
                pCompletionInfo->GetCompletionBytes());
            sprintf_s(szStatus,255,"Completion Status: 0x%08x",
                pCompletionInfo->GetCompletionStatus());

            // Create an array of strings.
            LPCSTR szBuffer[3] = {szNotification,szBytes,szStatus};
            // Write the strings to the Event Viewer.
            WriteEventViewerLog(szBuffer,3);
        }
        
        // Return processing to the pipeline.
        return RQ_NOTIFICATION_CONTINUE;
    }

    MyHttpModule(void)
    {
        // Open a handle to the Event Viewer.
        m_hEventLog = RegisterEventSource( NULL,"IISADMIN" );
    }

    ~MyHttpModule(void)
    {
        // Test if the handle for the Event Viewer is open.
        if (NULL != m_hEventLog)
        {
            // Close the handle to the Event Viewer.
            DeregisterEventSource( m_hEventLog );
            m_hEventLog = NULL;
        }
    }

private:

    // Handle for the Event Viewer.
    HANDLE m_hEventLog;

    // Define a method that writes to the Event Viewer.
    BOOL WriteEventViewerLog(LPCSTR * lpStrings, WORD wNumStrings)
    {
        // Test whether the handle for the Event Viewer is open.
        if (NULL != m_hEventLog)
        {
            // Write any strings to the Event Viewer and return.
            return ReportEvent(
                m_hEventLog, EVENTLOG_INFORMATION_TYPE,
                0, 0, NULL, wNumStrings, 0, lpStrings, NULL );
        }
        return FALSE;
    }
};

// Create the module's class factory.
class MyHttpModuleFactory : public IHttpModuleFactory
{
public:
    HRESULT
    GetHttpModule(
        OUT CHttpModule ** ppModule, 
        IN IModuleAllocator * pAllocator
    )
    {
        UNREFERENCED_PARAMETER( pAllocator );

        // Create a new instance.
        MyHttpModule * pModule = new MyHttpModule;

        // Test for an error.
        if (!pModule)
        {
            // Return an error if we cannot create the instance.
            return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY );
        }
        else
        {
            // Return a pointer to the module.
            *ppModule = pModule;
            pModule = NULL;
            // Return a success status.
            return S_OK;
        }            
    }

    void Terminate()
    {
        // Remove the class from memory.
        delete this;
    }
};

// Create the module's exported registration function.
HRESULT
__stdcall
RegisterModule(
    DWORD dwServerVersion,
    IHttpModuleRegistrationInfo * pModuleInfo,
    IHttpServer * pGlobalInfo
)
{
    UNREFERENCED_PARAMETER( dwServerVersion );
    UNREFERENCED_PARAMETER( pGlobalInfo );

    return pModuleInfo->SetRequestNotifications(
        new MyHttpModuleFactory,
        RQ_BEGIN_REQUEST | RQ_MAP_REQUEST_HANDLER,
        0
    );
}

모듈은 RegisterModule 함수를 내보내야 합니다. 프로젝트에 대한 모듈 정의(.def) 파일을 만들어 이 함수를 내보내거나 스위치를 사용하여 /EXPORT:RegisterModule 모듈을 컴파일할 수 있습니다. 자세한 내용은 연습: 네이티브 코드를 사용하여 Request-Level HTTP 모듈 만들기를 참조하세요.

필요에 따라 각 함수에 대한 호출 규칙을 명시적으로 선언하는 대신 호출 규칙을 사용하여 __stdcall (/Gz) 코드를 컴파일할 수 있습니다.

요구 사항

형식 Description
클라이언트 - Windows Vista의 IIS 7.0
- Windows 7의 IIS 7.5
- Windows 8의 IIS 8.0
- WINDOWS 10 IIS 10.0
서버 - Windows Server 2008의 IIS 7.0
- Windows Server 2008 R2의 IIS 7.5
- Windows Server 2012의 IIS 8.0
- Windows Server 2012 R2의 IIS 8.5
- WINDOWS SERVER 2016 IIS 10.0
제품 - 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

참고 항목

CHttpModule 클래스