ASP.NET: Register HttpModule at runtime
In the last post, we have seen how we can use PreApplicationStartMethod assembly level attribute to configure ASP.NET application at runtime. Taking it further, in this post we will see how to leverage PreApplicationStartMethod to register HTTP module dynamically at runtime. You can read more on PreApplicationStartMethod in this post here.
First of all we need to install/reference Microsoft.Web.Infrastructure assembly which provide API for registering HTTP module dynamically. To install Microsoft.Web.Infrastructure, type following in the Package Manager Console.
Once you installed Microsoft.Web.Infrastructure, you can use following code to register HTTP module runtime.
public class PreApplicationStart
{
public static void Start()
{
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility
.RegisterModule(typeof(MyHttpModule));
}
}
Please not that we can’t call above API from within Application_Start because HTTP module registration must be done before ASP.NET application start and it will throw an exception if you call it from other than PreApplicationStartMethod.
Hope this would be helpful and stay tuned for next post in a row on MVC 4. You can also follow me to get latest update via @NandipMakwana.