Freigeben über


Writing a simple ISAPI Extension

As my love on IIS increases, I wanted to try my hands on all the classic technologies available before I make myself ready for IIS 7. So, I started with a simple ISAPI Filter, and made that as a Bad one and took ETW trace to find out what is going behind the scenes. Now, I wrote a simple ISAPI Extension. ISAPI Extensions are the real functional part of IIS in terms of request processing and sending the response back to the client. You can read about ISAPI Extensions using the below links:

https://msdn.microsoft.com/library/en-us/vccore98/HTML/_core_internet_server_api_.28.isapi.29_.extensions.asp

https://www.codeproject.com/isapi/isapi_extensions.asp

https://msdn.microsoft.com/library/default.asp?url=/library/en-us/iissdk/html/8753b023-370f-45f7-b1af-c420be196743.asp

I have given my sample code below. This is a very simple ISAPI Extension, which just prints some text on the screen whenever it is invoked. As in ISAPI Filters, you have two main functions and an optional function which are needed to be exported.

1. GetExtensionVersion

2. HttpExtensionProc

3. TerminateExtension (optional)

Follow the steps in my previous article explaining how to create a project in VS.NET and creating a .DEF file. Below is the full source code:

#include <stdio.h>

#include <stdlib.h>

#include <afx.h>

#include <afxisapi.h>

void OutputToClient(EXTENSION_CONTROL_BLOCK *pEcb, LPSTR controlString, ...);

void SendHTMLHeader(EXTENSION_CONTROL_BLOCK *pEcb);

BOOL WINAPI GetExtensionVersion(HSE_VERSION_INFO *pVer)

 {

            pVer->dwExtensionVersion = MAKELONG(HSE_VERSION_MINOR, HSE_VERSION_MAJOR);

            lstrcpyn(pVer->lpszExtensionDesc, "My ISAPI Extension", HSE_MAX_EXT_DLL_NAME_LEN);

            return TRUE;

 }

DWORD WINAPI HttpExtensionProc(EXTENSION_CONTROL_BLOCK *pEcb)

 {

            SendHTMLHeader(pEcb);

            OutputToClient(pEcb, "<html>");

            OutputToClient(pEcb, "<head><title>This is my output page!</title></head>");

            OutputToClient(pEcb, "<body bgcolor=#FFFFFF>Hello World! Output from ISAPI Extension. rakkimk@hotmail.com </body>");

            OutputToClient(pEcb, "</html>");

            return HSE_STATUS_SUCCESS;

 }

void OutputToClient(EXTENSION_CONTROL_BLOCK *pEcb, LPSTR ctrlStr, ...)

 {

            char buff[1024];

            va_list arPtr;

            DWORD buffsize;

            va_start(arPtr, ctrlStr);

            vsprintf(buff, ctrlStr, arPtr);

            size = strlen(buff);

            pEcb->WriteClient(pEcb->ConnID, buff, &buffsize, NULL);

 }

void SendHTMLHeader(EXTENSION_CONTROL_BLOCK *pEcb)

 {

            char MyHeader[4096];

            strcpy(MyHeader, "Content-type: text/html\n\n");

            pEcb->ServerSupportFunction(pEcb->ConnID, HSE_REQ_SEND_RESPONSE_HEADER, NULL, 0, (DWORD *) MyHeader);

 }

 

PS: This is just a sample one. Use at your own risk! J