Writing a module that can intercept requests in IIS7 is very easy. In fact, for people that have written HttpModules in ASP.NET before – this is nothing new at all.
The general idea is that you write a class that implements the IHttpModule interface and register it in the <modules> section in configuration. This interface defines two methods, Init and Dispose. Init is called during application startup and is used to hook up an event handler to one of the various request processing events, e.g. BeginRequest, AuthenticateRequest etc. In Dispose you get the chance to do resource cleanup if needed.
public interface IHttpModule
void Init(HttpApplication context);
Since the ServerHeader module wants to change the HTTP response headers, it seems appropriate to inject our code into the PreSendRequestHeaders event which occurs directly before the headers are sent out to the client. The following code does the event handler registration:
public void Init(HttpApplication context)
context.PreSendRequestHeaders += OnLeave;
To change a response header you use the HttpResponse.Headers collection. Changing response headers that don’t originate from managed code (in this case from the web core) is a new feature in IIS7 and is enabled by the integrated pipeline. The following code would throw an exception on IIS6:
void OnLeave(object sender, EventArgs e)
// set header
The last step is to compile this class into a .dll and copy it either into the /bin folder of an application or into the GAC. After that you can register the module at the configuration level you want to use it (machine, site or application). Add the following section to the corresponding web.config:
type=“LeastPrivilege.ServerHeader.ServerHeaderModule, … ” />
When you now make requests to IIS7 and inspect the response (e.g. with a tool like Fiddler), you can see that the value of the server header is to whatever you have set it in code. And btw – this is also the case if you request a static file like html or jpg. Managed modules get called for every single request now (at least by default).
OK – so that’s the core of the new IIS7 feature I want to add. It may look simple but this is a huge improvement. For the first time we can plug directly into IIS request processing using managed code and you can imagine all kinds of interesting scenarios you can realize with this possibility.
Next time I will talk about how to add a custom configuration section to web.config and how the module can read its configuration settings.