Thursday 11 February 2016

What is Httphandler and HttpModule in Asp.Net ?





ASP.NET handles all the HTTP requests coming from the user and generates the appropriate response for it. ASP.NET framework knows how to process different kind of requests based on extension, for example, It can handle request for .aspx, .ascx and .txt files, etc. When it receives any request, it checks the extension to see if it can handle that request and performs some predefined steps to serve that request.
ASP.NET default handlers:


  • Page Handler (.aspx) - Handles Web pages
  • User Control Handler (.ascx) - Handles Web user control pages
  • Web Service Handler (.asmx) - Handles Web service pages
  • Trace Handler (trace.axd) - Handles trace functionality


Now as a developer, we might want to have some of our own functionality plugged in. We might want to handle some new kind of requests or perhaps we want to handle an existing request ourselves to have more control on the generated response, for example, we may want to decide how the request for .jpg or .gif files will be handled. Here, we will need an HTTPHandler to have our functionality in place.



Example :

public class MyHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            if (context.Request.RawUrl.Contains(".cspx"))
            {
              
                string newUrl = context.Request.RawUrl.Replace(".cspx", ".aspx");
                context.Server.Transfer(newUrl);
            }
         }

      }



Now we need to add our handler in webConfig file to use it.

<httpHandlers>
    <add verb="*" path="*.cspx" type="MyHandler "/>
</httpHandlers>





What is HTTP module:

Help in processing of page request by handing application events , similar to what global.asax does. A request can pass through many HTTP modules but is being handled by only one HTTP handlers.



Use of HTTP Modules:

ASP.NET uses HTTP modules to enable features like caching, authentication, error pages etc.
<add> and <remove> tags can be used to add and inactive any http module from <httpmodule> section of a configuration file.


<add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
<add name="WindowsAuthentication"
type="System.Web.Security.WindowsAuthenticationModule"/>
<add name="FormsAuthentication"
type="System.Web.Security.FormsAuthenticationModule"/>
</httpModules>



Here I just explained about Httphandler and HttpModule. I hope its useful to readers. Please send your comments and feedback. Thank You.













No comments:

Post a Comment