HTTP modules intercept incoming requests and inject pre-processing logic in the ASP.Net request processing pipeline Credit: Thinkstock There are two ways in which you can inject logic in the request pipeline of an ASP.NET application — HttpHandlers and HttpModules. An HttpModule is a component that is part of the ASP.NET request processing pipeline and is called on every request that is made to your application. Note that HttpModules can have access to the life cycle events of a request and hence they can be used to modify the response as well. HttpModules are generally used for plugging in the cross cutting concerns like security, logging, etc. in the request processing pipeline and can also be used for URL re-writing and even for creating custom headers in the response. As Microsoft’s documentation states, “An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.” To create a custom HttpModule, you should create a class that implements the System.Web.IHttpModule interface. To create an HttpModule, follow these steps: Open Visual Studio IDE Click on File->New Project Create a class library project Add reference to System.Web assembly to this project Next, create a class inside this project that implements the IHttpModule interface Write a handler for the Init method to initialize your module and subscribe to one or more events Optionally, implement a Dispose method in your custom module At first glance, our custom HttpModule looks like this: public class IDGCustomHttpModule : IHttpModule { public void Dispose() { throw new NotImplementedException(); } public void Init(HttpApplication context) { throw new NotImplementedException(); } } The following code snippet shows how you can subscribe to events in your custom HTTP module. public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(OnBeginRequest); context.EndRequest += new EventHandler(OnEndRequest); context.LogRequest += new EventHandler(OnLogRequest); } Let’s now write the code for the OnLogRequest method. This method is intended to log the path or every request to a text file. Here’s how the OnLogRequest method should look: public void OnLogRequest(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; string filePath = @"D:IDGLog.txt"; using (StreamWriter streamWriter = new StreamWriter(filePath)) { streamWriter.WriteLine(context.Request.Path); } } The following code listing illustrates the complete custom HTTP module. public class IDGCustomModule: IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(OnBeginRequest); context.EndRequest += new EventHandler(OnEndRequest); context.LogRequest += new EventHandler(OnLogRequest); } public void OnLogRequest(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; string filePath = @"D:IDGLog.txt"; using (StreamWriter streamWriter = new StreamWriter(filePath)) { streamWriter.WriteLine(context.Request.Path); } } public void OnBeginRequest(object sender, EventArgs e) { //Write your custom code here } public void OnEndRequest(object sender, EventArgs e) { //Write your custom code here } public void Dispose() { //Write your custom code here to dispose any objects if needed } } The next step is to use the custom HTTP module. To do this, create another project (this time, an ASP.NET application project). First, build the solution and add reference to the custom HTTP module we just created. Next, you will need to register the custom HTTP module in the web.config file. The following code snippet illustrates how the custom HTTP module can be registered. <system.webServer> <modules> <add name="CustomHttpModule" type="IDGModule.IDGCustomModule, IDGCustomModule" /> </modules> </system.webServer> And, that’s all you need to do to use your custom HTTP module. When using a synchronous HTTP module, the thread would not be released until the request processing completes. This can become a major performance bottleneck when your custom HTTP module needs to perform long running I/O bound operations. To solve this, you can take advantage of asynchronous programming to implement an asynchronous HTTP module as well. This would ensure that the performance of your application doesn’t degrade when your HTTP module needs to do lot of processing. Asynchronous programming helps in better usage of available resources. To implement asynchrony in your custom HTTP module, you would want to leverage the EventHandlerTaskAsyncHelper class available as part of .NET Framework 4.5. The following code snippet illustrates how you can take advantage of this class to subscribe to events in the Init method of your custom HTTP module. Note that the LogRequest method should return an instance of type Task. public void Init(HttpApplication context) { EventHandlerTaskAsyncHelper asyncHelperObject = new EventHandlerTaskAsyncHelper(LogRequest); context.AddOnPostAuthorizeRequestAsync(asyncHelperObject.BeginEventHandler, asyncHelperObject.EndEventHandler); } Here is the complete code listing of the asynchronous version of our custom HTTP module. public class IDGCustomModule: IHttpModule { public void Init(HttpApplication context) { EventHandlerTaskAsyncHelper asyncHelperObject = new EventHandlerTaskAsyncHelper(LogRequest); context.AddOnPostAuthorizeRequestAsync(asyncHelperObject.BeginEventHandler, asyncHelperObject.EndEventHandler); } private async Task LogRequest(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; string filePath = @"D:IDGLog.txt"; using (StreamWriter streamWriter = new StreamWriter(filePath,true)) { await streamWriter.WriteLineAsync(context.Request.Path); } } } How to do more in ASP.NET and ASP.NET Core: How to use in-memory caching in ASP.NET Core How to handle errors in ASP.NET Web API How to pass multiple parameters to Web API controller methods How to log request and response metadata in ASP.NET Web API How to work with HttpModules in ASP.NET Advanced versioning in ASP.NET Core Web API How to use dependency injection in ASP.NET Core How to work with sessions in ASP.NET How to work with HTTPHandlers in ASP.NET How to use IHostedService in ASP.NET Core How to consume a WCF SOAP service in ASP.NET Core How to improve the performance of ASP.NET Core applications How to consume an ASP.NET Core Web API using RestSharp How to work with logging in ASP.NET Core How to use MediatR in ASP.NET Core How to work with session state in ASP.NET Core How to use Nancy in ASP.NET Core Understand parameter binding in ASP.NET Web API How to upload files in ASP.NET Core MVC How to implement global exception handling in ASP.NET Core Web API How to implement health checks in ASP.NET Core Best practices in caching in ASP.NET How to use Apache Kafka messaging in .NET How to enable CORS on your Web API When to use WebClient vs. HttpClient vs. HttpWebRequest How to work with Redis Cache in .NET When to use Task.WaitAll vs. Task.WhenAll in .NET Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos