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 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos