Click here to Skip to main content
Click here to Skip to main content

Tagged as

Asp.net HTTP Modules

, 13 Jan 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
HTTP Modules use to intercept HTTP requests for modifying or utilize HTTP based requests according to need.

ASP.NET HTTP Modules:

HTTP Modules:

HTTP Modules use to intercept HTTP requests for modifying or utilize HTTP based requests according to needs like authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching....

HTTP Modules are activated/called/invoked before and after HTTP Handler execution.

HTTP Modules are integral part of ASP.NET framework now and heavily being used as it cater grips upon request and let developers to generate response in a customized way, according to user requirement. Web development is all about playing with request from client to server and response from server to client.

When any request goes to web server, request passes through different phases and then at last response gets generate for client.

HTTP Modules are .Net based components/Plugins and programmed by implementing System.Web.IHTTPModule interface of .Net.

HTTP Module Background:

Before HTTP Modules, web developers/programmers used to implement Internet Server Application Programming Interface (ISAPI) Filters like me (wish interviewer asked me about by terms of ISAPI at that time then I tell him (Big Grin | :-D )), anyhow jokes apart.

As name implies ISAPI is a web server based API and used to manage request which comes to web server and generate response. ISAPI based upon web server (IIS) where as NSAPI is Netscape based web server API.

ISAPI is based upon win32 DLL and programmed in unmanaged code C/C++, which is somehow painful (:$) and due to unmanaged code, is less reliable, scalable and quite complex to implement than HTTP Modules by managed code under the framework of .Net. Hope you got it why ISAPI Filters replaced by HTTP Modules (;))

Asp.net requests goes through HTTP Modules events just like (oil flowing through pipeline and that pipeline has some filters to refine that oil)

HTTP Modules Events:

Every HTTP Module must implement following two methods of IHTTPModule interface:

Init: To register/initialize event handler to the events of HTTP Module for HTTP based application.

Dispose: To perform a clean up code means resource releasing, object removing from memory and such other resources releasing which used explicitly.

Following are list of events with their brief description:

BeginRequest: Event fired whenever any asp.net based request sent to web server. If you need to do perform at the beginning of a request for example, modify show banners, log HTTP Header information, Get/Set cultures, Response.Filter to generate response for browser according to your need.

AuthenticateRequest: If you want to check authentication of request that request comes from authenticated user or not means wants to implement custom authentication scheme. For example, look up a requested user credentials against a database to validate.

AuthorizeRequest: This method is used specifically to implement authorization mechanisms means authenticated user/request has what privileges/rights/access in that specific application for example, either user has access on all pages or not of that website or has write to create file or not or visit report pages and like this.

ResolveRequestCache: This event determines if a page served from the Output cache. If you want to write your own caching module (for example, build a file-based cache rather than a memory cache), synchronize this event to determine whether to serve the page from the cache.

AcquireRequestState: Session state is retrieved from the state store. If you want to build your own state management module, synchronize this event to grab the Session state from your state store.

PreRequestHandlerExecute: This event occurs before the HTTP handler is executed.

PostRequestHandlerExecute: This event occurs after the HTTP handler is executed.

ReleaseRequestState: Session state is stored back in the state store. If you are building a custom session state module, you must store your state back in your state store.

UpdateRequestCache: This event writes from output back to the Output cache. If you are building a custom cache module, you have to write the output back to your cache.

Error: this event always occurs when any exception (unhandled error occurs in application, this event specifically uses to handle or log error messages of that web application. (Heavily used in Error Logging Modules and Handlers (ELMAH) kind of applications). You can learn about ELMAH more from following link in detail: http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx

EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information on the page.

By above events list you must be getting wonder about difference between Global.asax as somehow events of Global.asax are pretty same, so let me tell you difference between Global.asax and HTTP Module (another common question asked in interviews)

But you need to register/initialize these Events explicitly in “Init” method; following is sample code of IHTTPModule implementation for couple of events.

"kwd">using System;
"kwd">using System.Web;
"kwd">using System.Collections;

"kwd">public class HelloWorldModule : IHttpModule
{
    "kwd">public String ModuleName
    {
        "kwd">get { "kwd">return "st">"HelloWorldModule"; }
    }

    "cmt">// In the Init function, register for HttpApplication 
    // events by adding your handlers.
    "kwd">public void Init(HttpApplication application)
    {
         application.BeginRequest += ("kwd">new EventHandler("kwd">this.Application_BeginRequest));
         application.EndRequest += ("kwd">new EventHandler("kwd">this.Application_EndRequest));

    }

    "cmt">// Your BeginRequest event handler.

    "kwd">private void Application_BeginRequest(Object source, EventArgs e)
    {
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        context.Response.Write("st">"&lt;h1><font color=red>HelloWorldModule: Beginning of Request</font></h1><hr>");
    }

    "cmt">// Your EndRequest event handler.

    "kwd">private void Application_EndRequest(Object source, EventArgs e)
    {
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        context.Response.Write("st">"&lt;hr><h1><font color=red>HelloWorldModule: End of Request</font></h1>");
    }
    "kwd">public void Dispose()
    {
    }
}

Ref: msdn

HTTP Module vs Global.asax

 

1. HTTP Module is pluggable component that’s why could be use for other web applications as well as on other server or in same server where as Global.asax couldn’t.

2. According to life cycle of Request, Request passed through HTTP Module first and then through Global.asax

3. Following are list of events which are supported in Global.asax but unfortunately not in HTTP Module.

  1. Application_OnStart
    This event is raised when the very first request passed through the web application.

  2. Application_OnEnd
    This event is raised just before the application is going to terminate.

  3. Session_OnStart
    This event is raised for the very first request of the user's session.

  4. Session_OnEnd
    This event is raised when the session is abandoned or expired.

Here I would like to share one more interview experience of me but now its about my friend’s interview, for which he did preparation from me/took my help or guidance for it Anyhow whilst I was helping him in his preparation for asp.net technical interview, I asked him: “ tell me when session starts?” He replied: “Simple when user logins from login page”, I said ok! Suppose site has no login page and could be accessible by anonymous user, session will never start and Session_OnStart event of Global.asax will never fire then is it? He replied: of course, I couldn’t stop me to smile; I might not laugh if he has no experience or less experience but he has more than 4 years of experience. Anyhow next day when he went for interview, interviewer asked him the same question and he smiled and said, “If you think I will say when user login session_Onstart event will fire then you are wrong. (They also started laughing).

Anyhow normally people say or according to books to tell reader in easy way that session are user based, NO! Sessions are actually browser based. Anyhow shouldn’t go away from topic as much.

Registering HTTP Module

The following is an example of registering/adding an HTTP module:

  <httpModules>    <add type="ClassName, AssemblyName" name="ModuleName" />  <httpModules>

 

The following is a general example of removing an HTTP module from web application.

 

  <httpModules>    <remove name="ModuleName" />  <httpModules>

 

All code suppose to be in either web.config or in machine.config

Following is the list of module is defined at machine.config or web.config by default. ($WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG\ CONFIG Files)

 

<httpModules><add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/><add name="Session" type="System.Web.SessionState.SessionStateModule"/><add name="WindowsAuthentication" ="System.Web.Security.WindowsAuthenticationModule"/><add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/><add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"/><add name="RoleManager" type="System.Web.Security.RoleManagerModule"/><add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/><add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/><add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule"/><add name="Profile" type="System.Web.Profile.ProfileModule"/><add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/><add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/></httpModules>

Performance:

You can improve performance of your application by removing default (but not in used) HTTP Modules registered in machine.config file as these are activated/invoked/called on each request for your application unnecessarily by <remove …> for example,

 

<httpModules>    <!-- Remove unnecessary Http Modules for faster pipeline -->     <remove name="Session" />      <remove name="WindowsAuthentication" />     <remove name="PassportAuthentication" />     <remove name="AnonymousIdentification" />     <remove name="UrlAuthorization" />

 

     <remove name="FileAuthorization" />     <remove name="OutputCache" />     <remove name="RoleManager" />     <remove name="Profile" />     <remove name="ErrorHandlerModule" />     <remove name="ServiceModel" />  </httpModules>

But please make sure before its implementation/applying that you are not using them. If you are using any of these, you may exclude that from existing list.

Conclusion

HTTP Modules are quite simple to understand and quite flexible by means of its number of events. HTTP modules integrate with whole application and every request passed through HTTP Module. So HTTP Module should be implemented very carefully. Take the time to completely understand its advantages, disadvantages, implementation and concepts before implementing a solution.

To get more detailed understanding of HTTP Modules with real time examples implmentation, I would recommend you to visit following links:

 

Recommended Links:

For URL Redirection example click here

For Security based example click here

For IP based security example click here

For Error Manager Example click here

For Videos click here and  here

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Adnan Aman
Software Developer (Senior)
Pakistan Pakistan
computer science graduate. design and develop software using .net technologie

Comments and Discussions

 
QuestionMy vote of 4 Pinmembern_zaheer_ahmed21-Apr-14 6:27 
GeneralMy vote of 2 PinmemberRyan Leeder1-Nov-09 16:53 
GeneralMy vote of 1 PinmemberTodd Smith13-Jan-09 9:07 
Doesn't even pass basic formatting requirements.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 13 Jan 2009
Article Copyright 2009 by Adnan Aman
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid