How to register a custom HTTP module in your .NET web application
July 10, 2015 2 Comments
You can easily add your custom HTTP module to a .NET web application. Here’s an excerpt from the MSDN article referenced in the previous sentence:
“An HttpModule is an assembly that implements the IHttpModule interface and handles events. ASP.NET includes a set of HttpModules that can be used by your application.”
If you have a web application, e.g. an MVC or Web API (2) project then you can add a custom HTTP module as follows.
Add a class that implements the IHttpModule interface. Here’s an implementation stub which shows the 2 methods that need to be implemented:
namespace HttpModuleTestApplication.Modules { public class TestModule : IHttpModule { public void Dispose() { throw new NotImplementedException(); } public void Init(HttpApplication context) { throw new NotImplementedException(); } } }
The Init method initialises a module. You can sign up for events available in the incoming HttpApplication object. This page on MSDN lists all the available events which you can attach an event handler to. Some of them such as BeginRequest and RequestCompleted will sound familiar to all .NET web developers.
The Dispose method implementation is optional. It’s there for any resource cleanup, we’ll ignore it for this basic example.
Let’s sign up for two events:
namespace HttpModuleTestApplication.Modules { public class TestModule : IHttpModule { public void Dispose() {} public void Init(HttpApplication context) { context.BeginRequest += context_BeginRequest; context.RequestCompleted += context_RequestCompleted; } void context_RequestCompleted(object sender, EventArgs e) { Debug.WriteLine("Context_RequestCompleted event fired."); } void context_BeginRequest(object sender, EventArgs e) { Debug.WriteLine("Context_BeginRequest event fired."); } } }
The module needs to be registered. It can be added to the web.config file within the system.webServer node:
<system.webServer> <modules> <add name="DescriptiveNameOfModule" type="HttpModuleTestApplication.Modules.TestModule"/> </modules> </system.webServer>
We add the individual custom modules within the modules node. The add element has a name and a type property. Name can be pretty much anything so select a descriptive name. The type must be the fully qualified name of the module including the namespace and the class name.
If you run your web application you should see that the registered events will be fired.
View all various C# language feature related posts here.
Or by using Web Activator: https://github.com/davidebbo/WebActivator
Almost 5 years later I used this info to implement an HTTP module that sets thread culture from a cookie. Thank you