Wednesday, September 25, 2013

Intercept calls coming to a Web Application in IIS Server



It was required to intercept all the calls coming into a particular web application on the IIS Server and identify the contents in the request. We ended up writing a class derived from “IHttpModule" interface.
Here are some tips on how to create and install it on the IIS server.
  • Creating the class is a simple task. Just derive the class from the interface “IHttpModule". Implement the interface as shown below.

public class ServerIntercept : IHttpModule
{
      public void Dispose()
       {
       }
       public void Init(HttpApplication context)
       {
        context.BeginRequest += context_BeginRequest;
        }
        void context_BeginRequest(object sender, EventArgs e)
        {
            // Add all code here
        }
}

  • Make sure the DLL is signed with strong name key
  • Copy this DLL to the server and use GAC utility to register this on the server.  If it is .NET 2 framework it is a different utility and if it is .NET 4 framework it is a different utility. Use the correct utility to register.
  • Add the entries to the Web.Config file of the application. This file may be read-only. Make sure the entries are being saved properly. A sample is shown below.
<configuration>
<system.webServer>
<modules>
<add name="ScriptModule-4.0" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler,runtimeVersionv4.0" />
</modules>
</system.webServer>
</configuration>

 The type in the above example is the class name with namespace and the DLL file name. The public key token value can be obtained from the GAC utility.
  • Reset IIS. Then open the IIS manager. Go to the application and look into the “Modules” section. The newly installed module must be present and now the application is ready to intercept all the calls coming to it.

Happy coding!

All Blogs so far ...