Condividi tramite


Metodo CHttpModule::OnAsyncCompletion

Rappresenta il metodo che gestirà un evento di completamento asincrono, che si verifica dopo la fine dell'elaborazione di un'operazione asincrona.

Sintassi

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

Parametri

pHttpContext
[IN] Puntatore a un'interfaccia IHttpContext .

dwNotification
[IN] Valore DWORD contenente la maschera bit per la notifica correlata.

fPostNotification
[IN] true per indicare che la notifica è per un post-evento; in caso contrario, false.

pProvider
[IN] Puntatore a un'interfaccia IHttpEventProvider .

pCompletionInfo
[IN] Puntatore a un'interfaccia IHttpCompletionInfo .

Valore restituito

Valore REQUEST_NOTIFICATION_STATUS .

Commenti

A differenza di molti degli altri metodi CHttpModule chiamati dalla registrazione per notifiche specifiche, IIS chiamerà il metodo di un modulo solo al termine di OnAsyncCompletion un'operazione asincrona. Ad esempio, quando un modulo a livello di richiesta chiama il metodo IHttpResponse::WriteEntityChunks e specifica il completamento asincrono, IIS chiamerà il metodo del modulo al termine dell'operazione OnAsyncCompletion .

Quando IIS chiama il OnAsyncCompletion metodo, specifica il tipo di notifica nel dwNotification parametro e indicherà se la notifica era per un evento o un evento post-evento usando il fPostNotification parametro . IIS fornisce anche un'interfaccia IHttpCompletionInfo a cui punta il pCompletionInfo parametro. È possibile usare questa interfaccia per recuperare informazioni aggiuntive sul completamento asincrono.

Esempio

Nell'esempio di codice seguente viene illustrato come creare un modulo HTTP che esegue le attività seguenti:

  1. Il modulo registra le notifiche di RQ_BEGIN_REQUEST e RQ_MAP_REQUEST_HANDLER .

  2. Il modulo crea una CHttpModule classe contenente i metodi OnBeginRequest, OnMapRequestHandler e .OnAsyncCompletion

  3. Quando un client Web richiede un URL, IIS chiama il metodo del OnBeginRequest modulo. Questo metodo esegue le attività seguenti:

    1. Cancella il buffer di risposta esistente e imposta il tipo MIME per la risposta.

    2. Crea una stringa di esempio e restituisce tale valore al client Web in modo asincrono.

    3. Verifica un errore o un completamento asincrono. Se il completamento asincrono è in sospeso, il modulo restituisce uno stato di notifica in sospeso alla pipeline di elaborazione della richiesta integrata.

  4. IIS chiama il metodo del OnMapRequestHandler modulo. Questo metodo esegue le attività seguenti:

    1. Scarica il buffer di risposta corrente nel client Web.

    2. Verifica un errore o un completamento asincrono. Se il completamento asincrono è in sospeso, il modulo restituisce lo stato di notifica in sospeso alla pipeline.

  5. Se è necessario il completamento asincrono, IIS chiama il metodo del OnAsyncCompletion modulo. Questo metodo esegue le attività seguenti:

    1. Test per un'interfaccia valida IHttpCompletionInfo . Se è stata passata un'interfaccia validaIHttpCompletionInfo, il metodo chiama rispettivamente i metodi GetCompletionBytes e GetCompletionStatus per recuperare i byte completati e restituire lo stato per l'operazione asincrona.

    2. Crea stringhe che contengono le informazioni di completamento e scrive le informazioni come evento nel log dell'applicazione del Visualizzatore eventi.

  6. Il modulo rimuove la CHttpModule classe dalla memoria e quindi chiude.

#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
    );
}

Il modulo deve esportare la funzione RegisterModule . È possibile esportare questa funzione creando un file di definizione del modulo (con estensione def) per il progetto oppure è possibile compilare il modulo usando l'opzione /EXPORT:RegisterModule . Per altre informazioni, vedere Procedura dettagliata: Creazione di un modulo HTTP Request-Level tramite codice nativo.

Facoltativamente, è possibile compilare il codice usando la __stdcall (/Gz) convenzione chiamante anziché dichiarare esplicitamente la convenzione chiamante per ogni funzione.

Requisiti

Tipo Descrizione
Client - IIS 7.0 in Windows Vista
- IIS 7.5 in Windows 7
- IIS 8.0 in Windows 8
- IIS 10.0 in Windows 10
Server - IIS 7.0 in Windows Server 2008
- IIS 7.5 in Windows Server 2008 R2
- IIS 8.0 in Windows Server 2012
- IIS 8.5 in Windows Server 2012 R2
- IIS 10.0 in Windows Server 2016
Prodotto - 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
Intestazione Httpserv.h

Vedere anche

Classe CHttpModule