Http Handler and Http Modules

HTTP HANDLERS. - Vishal Nayan

http://www.c-sharpcorner.com/uploadfile/37db1d/create-your-first-http-handler-in-Asp-Net-3-5/

What is HTTP handler: Every request into an ASP.NET application is handled by a specialized component known as an HTTP handler. The HTTP handler is the most important ingredient while handling ASP.NET requests.

Examples: ASP.NET uses different HTTP handlers to serve different file types. For example, the handler for web Page creates the page and control objects, runs your code, and renders the final HTML.

ASP.NET default handlers:
  1. Page Handler (.aspx) - Handles Web pages
  2. User Control Handler (.ascx) - Handles Web user control pages
  3. Web Service Handler (.asmx) - Handles Web service pages
  4. Trace Handler (trace.axd) - Handles trace functionality
Why we need to create our own HTTP Handler: Sometime we need to avoid ASP.NET full page processing model, which saves lot of overheads, as ASP.NET web form model has to go through many steps such as creating web page objects, persisting view state etc. What we are interested into is to develop some low level interface that provides access to objects like Request and Response but doesn't use the full control based web form model discussed above.

Examples:
  1. Dynamic image creator - Use the System.Drawing classes to draw and size your own images.
  2. RSS - Create a handler that responds with RSS-formatted XML. This would allow you to add RSS feed capabilities to your sites.
  3. Render a custom image,
  4. Perform an ad hoc database query,
  5. Return some binary data.
These examples extend the ASP.NET architecture but bypass the web-page model. The result is a leaner, more efficient component.

Where HTTP handlers are defined: All HTTP handlers are defined in the <httpHandlers> section of a configuration file which is nested in the <system.web> element.

<httpHandlers>
<add verb="*" path="trace.axd" validate="true" type="System.Web.Handlers.TraceHandler"/>
<add verb="*" path="*.config" validate="true" type="System.Web.HttpForbiddenHandler"/>
<add verb="*" path="*.cs" validate="true" type="System.Web.HttpForbiddenHandler"/>
<add verb="*" path="*.aspx" validate="true" type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>
  1. Trace.axd : this handler is meant for rendering HTML page with a list of all the recently collected trace output, and this is handled by TraceHandler
  2. .config: Handled by HttpForbiddenHandler
  3. .cs: Handled by HttpForbiddenHandler
  4. .aspx: Handled by PageHandlerFactory, which isn't a HTTP handler rather it's a class that will create the appropriate HTTP handler.
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:
  1. ASP.NET uses HTTP modules to enable features like caching, authentication, error pages etc.
  2. <add> and <remove> tags can be used to add and inactive any http module from <httpmodule> section of a configuration file.
<httpModules>
<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>

Note:
  1. HTTP handler plays same role what ISAPI extension
  2. HTTP module plays same role what ISAPI filters does.
How to write custom HTTP handler:

Step 1: What all we need to know before writing handlers

There are two type of handler you actually can make
  1. Synchronous handler , which implement IHttpHandler interface
  2. Asynchronous handler, which implement IHttpAsyncHandler. With asynchronous handlers additional requests can be accepted, because the handler creates a new thread to process each request rather than using the worker process
Further these Interfaces require us to implement the ProcessRequest method and the IsReusable property.
  1. The ProcessRequest method handles the actual processing for requests made.
    ASP.NET calls this method when a request is received. It's where the HTTP handlers perform all the processing. You can access the intrinsic ASP.NET objects (such as Request, Response, and Server) through the HttpContext object that's passed to this method.
     
  2. Boolean IsReusable property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request. 
    After ProcessRequest() finishes its work, ASP.NET checks this property to determine whether a given instance of an HTTP handler can be reused. If it returns true, the HTTP handler object can be reused for another request of the same type current. If it returns false, the HTTP handler object will simply be discarded.
Step 2: Create a ASP.NET web application and name it: SimpleHTTPHanlder

Step 3: Add a class and name it "SimpleHandler"

Step 4: Write below code



Here we are implementing IHttpHandler 

Full code look like below
public class SimpleHandler : IHttpHandler    {        #region IHttpHandler Members
        bool IHttpHandler.IsReusable
        {
            get { return true; }
        }
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            HttpResponse response = context.Response;
            response.Write("<html><body><h1>Wow.. We created our first handler");
            response.Write("</h1></body></html>");
        }
        #endregion    }

Step 5: Configuring HTTP handler in configuration file;

We will add our handler in <httpHandlers> section
<httpHandlers>          <add verb="*" path="vishal.nayan"type="MyHttpHandler.SimpleHandler,MyHttpHandler"/></httpHandlers>

Now here we need to understand what these attributes means
  1. Verb: indicates whether the request is an HTTP POST or HTTP GET request (use * for all requests).
  2. Path : indicates the file extension that will invoke the HTTP handler
  3. Type: identifies the HTTP handler class. This identification consists of two portions. First is the fully qualified class name , That portion is followed by a comma and the name of the DLL assembly that contains the class
Step 6: How to run our Handler

Well, visual studio doesn't allow us directly to run the handler, rather we need to run the project first and then explicitly type URL to request for handler, so in our case it is;

http://localhost:3238/myhttphandler/vishal.nayan

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6