Wednesday 25 December 2013

Usage of IHttpHandler and IHttpModule in ASP.Net

In this article we are going to see the usage of IHttpHandler and IHttpModule and the implementation of that in web application. Both are used for implement the preprocessing logic in request pipeline.

Following are the steps takes place while user request a page or file in a browser.

user request 
           -> BeginRequest 
           -> authenticate Request 
           -> Authorize Request
           -> PreRequestHandlerExecute
                ->  [ HttpHandler ]
           -> PostRequestHandlerExecute
           -> End Request
      
In this sample we are taking a sample that whenever a user request a file extension with .aspx we are change it to the .yv extension using HttpModule , Then write a handler for the .yv extension how to process the request of file extension .yv. This is almost like UrlRewrite sample with different extension

IHttpModule
       IHttpModule is used to implement the event based preprocessing logic, Implement the IHttpModule and Register the events which are need to execute in the module.

Two things that need to be implement is Dispose and Init in IHttpmodule

Events that are takes place in the HttpModule 

  •            BeginRequest 
  •            Authenticate Request 
  •            Authorize Request
  •            PreRequestHandlerExecute             
  •            PostRequestHandlerExecute
  •            End Request

Now we are going to register the BeginRequest event for implement the pre-processing logic. In this we are creating a log who are all giving request at which time to which file.

namespace WebApp
{

    public class CustomModule : IHttpModule
    {       
        public CustomModule()
        {

        }

        public void Dispose()
        {
          
        }

        public void Init(HttpApplication context)
        {                       
            /* Register a Event of a Request PipeLine */
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }

        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
         
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication appli = sender as HttpApplication;
            StreamWriter logwriter = new StreamWriter(appli.Server.MapPath(@"~\Files\log.txt"),true);
            logwriter.Write("Request has been raised at "+DateTime.Now.ToString()+" for "+appli.Request.RawUrl);
            logwriter.Close();
           
            string url = appli.Request.RawUrl;
            if (url.Contains(".aspx"))
            {
                string rewriteurl = url.Replace(".aspx", ".yv");
                appli.Response.Redirect(rewriteurl);
            }

        }
} 

Log Information:
Request has been raised at 25-12-2013 19:40:01 for /AddEmployee.aspx

Request has been raised at 25-12-2013 19:40:04 for /AddEmployee.yv

IHttpHandler 
       IHttphandler is used to implement the preprocessing logic based on the extension of requested file type, implement the IHttpHandler by implement the ProcessRequest and IsResuable in the class.

In this handler we are going to handler the request of file type with extension .yv.

namespace WebApp
{

   public class CustomHandler:IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Server.Transfer(context.Request.RawUrl.Replace(".yv",".aspx"));
        }
    }

} 

Web.Config
    In web.config we have to specify the settings in two place one is in System.web and another in system.WebServer, because if you not specify in system.Webserver it will not reflect in IIS only reflect in visual studio development server.please specify  the runAllManagedModulesForAllRequests  as True

<system.web>
   <httpHandlers>   
      <add verb="*" path="*.yv" type="WebApp.CustomHandler, WebApp"/>     
    </httpHandlers>
    <httpModules>
      <add name="UrlReWrite" type="WebApp.CustomModule, WebApp"/>
    </httpModules>
  </system.web>

<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
 
   <modules runAllManagedModulesForAllRequests="true">
      <remove name="ScriptModule"/>
      <add name="UrlReWrite" type="WebApp.CustomModule, WebApp"/>    
    </modules>
   
 <handlers>      
      <remove name="extensionhandler"/>
      <add name="extensionhandler" verb="*" path="*.yv" type="WebApp.CustomHandler, WebApp"/>     
    </handlers>
  </system.webServer>


Output:
     In the below image you can see that the user request a url with file extension of .aspx , but it changes to .yv and the file with .yv is processed successfully by handler.Third display shows the output.




From this article you can learn how to implement the IHttpHandler and IHttpModule and what is the usage of that in web application.

No comments:

Post a Comment