HttpModule basics

By | April 14, 2018

The a HTTP module is used when you need to intercept and examine the incoming HTTP requests before or after the page life cycle. The HTTPModule provides events where you can plug into to examine or alter the request or  response within the asp.net cycle. HTTPModule are the perfect place the apply security checks.

The basics.

The HttpModule must inherit from IHTTPModule. You need to subscribe to all the events that you need to monitor within the Init Method.

public class AuthenticationModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(this.OnBeginRequest);
application.AuthenticateRequest += new EventHandler(this.OnAuthenticateRequest);
application.EndRequest += new EventHandler(this.OnEndRequest);
}

public void OnBeginRequest(object sender, EventArgs e)
{

}

protected virtual void OnAuthenticateRequest(object sender, EventArgs args)
{

}

public void OnEndRequest(object sender, EventArgs e)
{

}
}

Plugging it in

To plug the HTTPModule into the asp.net pipeline you need to do a bit of configuration.

The order of your module does matter. When a request is received .net will route the request through every HTTPModule in the order that it is registered.

<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="AuthenticationModule" type="Company.Product.Layer.AuthenticationModule" preCondition="managedHandler" />
</modules>
</system.webServer>

The HTTPModule pipeline

As a request is received it is routed through every Module and will execute the events in the following order.

Pre – Page Life Cycle

  • BeginRequest
  • AuthenticateRequest
  • AuthorizeRequest
  • ResolveRequestCache
  • AcquireRequestState
  • PreRequestHandlerExecute

Post – Page life cycle

  • PostRequestHandlerExecute
  • ReleaseRequestState
  • UpdateRequestCache
  • EndRequest

Conclusion

I have not gone into a lot of detail here and have just provided enough knowledge to get going. Hope it helps.

Leave a Reply

Your email address will not be published.