httphandler and httpmodule in asp.net

An HTTP module is an assembly that is called on every request that is made to your application (for pre-processing logic implementation).
HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

There are multiple event invoke during httpmodule some of them are below.
  • BeginRequest - The BeginRequest event signals the creation of any given new request. This event is always raised and is always the first event to occur during the processing of a request.
  • AuthenticateRequest - The AuthenticateRequest event signals that the configured authentication mechanism has authenticated the current request. Subscribing to the AuthenticateRequest event ensures that the request will be authenticated before processing the attached module or event handle.
  • PostAuthenticateRequest - The PostAuthenticateRequest event is raised after the AuthenticateRequest event has occurred. All the information available is accessible in the HttpContext’s User property.
  • AuthorizeRequest - The AuthorizeRequest event signals that ASP.NET has authorized the current request. You can subscribe to the AuthorizeRequest event to perform custom authorization.
  • PostAuthorizeRequest - Occurs when the user for the current request has been authorized.
  • ResolveRequestCache - Occurs when ASP.NET finishes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the event handler and calling any EndRequest handlers.
  • PostResolveRequestCache – Reaching this event means the request can’t be served from the cache, and thus a HTTP handler is created here. A Page class gets created if an aspx page is requested.
  • MapRequestHandler - The MapRequestHandler event is used by the ASP.NET infrastructure to determine the request handler for the current request based on the file-name extension of the requested resource.
  • PostMapRequestHandler - Occurs when ASP.NET has mapped the current request to the appropriate HTTP handler.
  • AcquireRequestState - Occurs when ASP.NET acquires the current state (for example, session state) that is associated with the current request. A valid session ID must exist.
  • PostAcquireRequestState - Occurs when the state information (for example, session state or application state) that is associated with the current request has been obtained.
  • PreRequestHandlerExecute - Occurs just before ASP.NET starts executing an event handler.
  • ExecuteRequestHandler – Occurs when handler generates output. This is the only event not exposed by the HTTPApplication class.
  • PostRequestHandlerExecute - Occurs when the ASP.NET event handler has finished generating the output.
  • ReleaseRequestState - Occurs after ASP.NET finishes executing all request event handlers. This event signal ASP.NET state modules to save the current request state.
  • PostReleaseRequestState - Occurs when ASP.NET has completed executing all request event handlers and the request state data has been persisted.
  • UpdateRequestCache - Occurs when ASP.NET finishes executing an event handler in order to let caching modules store responses that will be reused to serve identical requests from the cache.
  • PostUpdateRequestCache - When thePostUpdateRequestCache is raised, ASP.NET has completed processing code and the content of the cache is finalized.
  • LogRequest - Occurs just before ASP.NET performs any logging for the current request. The LogRequest event is raised even if an error occurs. You can provide an event handler for the LogRequest event to provide custom logging for the request.
  • PostLogRequest - Occurs when request has been logged.
  • EndRequest - Occurs as the last event in the HTTP pipeline chain of execution when ASP.NET responds to a request. In this event, you can compress or encrypt the response.
  • PreSendRequestHeaders – Fired after EndRequest if buffering is turned on (by default). Occurs just before ASP.NET sends HTTP headers to the client.
  • PreSendRequestContent - Occurs just before ASP.NET sends content to the client.

We can register these events with the HttpModules. So when the request pipe line executes depending on the event registered, the logic from the modules is processed.


public class Module:IHttpModule
{
 public Module()
 {
   // TODO: Add constructor logic here
 }
 #region IHttpModule Members

 public void Dispose()
 {
    //Do Work
 }

 public void Init(HttpApplication context)
 {
  context.BeginRequest += new EventHandler(context_BeginRequest);
  context.EndRequest += new EventHandler(context_EndRequest);
 }

 void context_EndRequest(object sender, EventArgs e)
 {
    //Do Work
 }
 void context_BeginRequest(object sender, EventArgs e)
 {
    //Do Work
 }
 #endregion
}

// Web Config Setting

<system.web>

  <httpModules>
      <add name="PPCModule" type="PPCModule" />
      <add type="Module" name="Module" />
  </httpModules>


Http Handler : -

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.

The HttpHandler is a pre-processing logic implementation blocks and is the part of the ASP.NET request pipeline. Whenever the IIS Server recieves a request, it looks for an ISAPI filter(looking for the perticuler httphandler to handle a perticuler extension) that is capable of handling web requests.

ASP.NET maps HTTP requests to HttpHandlers. Each HttpHandler enables processing of individual HTTP URLs or groups of URL extensions within an application. 

 

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 

Handlers are considered to be more lightweight object than pages. That's why they are used to serve dynamically-generated images, on-the-fly generated PDF-files and similar content to the web browser.

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.
 


public class htmHandler: IHttpHandler
{
  public htmHandler()
  {
      // TODO: Add constructor logic here
  }

  #region IHttpHandler Members

  public bool IsReusable
  {
      get { return false; }
  }

 public void ProcessRequest(HttpContext context)
 {
    context.Response.ContentType = "text/plain";
    if (context.Request.RawUrl.Contains("fake.htm"))
    {
      string MainUrl = context.Request.RawUrl.Replace("fake.htm", "menu.aspx");
      context.Server.Transfer(MainUrl);
    }
   }

    #endregion
}

// Web Config Setting
<system.web>

  <httpHandlers >
      <add verb="*" path="*.htm" type="htmHandler" />
  </httpHandlers>


Below is the figure representation of working flow of httphandler and httpmodule showing that one extension handled by only one particular handler while one httphandler can handle multiple extension requests,first request comes to iis and then goes to iis pipeline then pre module events invoke then request go to the particular httphandler (according to the extension of page) and then post module event invoke ..

If We are hosting your application in IIS 7 then you have to do some additional setting in IIS 7 to be register httphandler and httpmodule in IIS 7 take look at this link below.



Recent Article