web analytics

Understanding HTTP Handlers and HTTP Modules in ASP.NET

Options
@2017-01-09 22:23:01

Under IIS 7 or later version, you have to specify custom http handlers and modules under the configuration/system.webServer/handlers element of your web.config.

The <handlers> element contains a collection of <add> elements, each of which defines a handler mapping for the application. The <add> element contains the name of the handler, the file name extension or URL path mask that the handler is mapped to, and the module name or ASP.NET HTTP handler type that specifies the handler implementation, among other settings.

The following example contains two <add> elements that define handler mappings. The first <add> element defines a SampleHandler handler for a Web application running in IIS 7 Integrated mode. If you add the handler assembly to the app_code directory for the Web application, you do not need to include the assembly name in the value for the type attribute. The second <add> element defines a mapping for PHP requests that use the FastCGI module.

<handlers>
   <add name="SampleHandler" verb="*" 
      path="SampleHandler.new" 
      type="SampleHandler, SampleHandlerAssembly" 
      resourceType="Unspecified" />
   <add name="PHP-FastCGI" verb="*" 
      path="*.php" 
      modules="FastCgiModule"
      scriptProcessor="c:\php\php-cgi.exe" 
      resourceType="Either" />
</handlers>
@2017-01-09 22:30:28

The httpHandlers element is used on sites running on IIS 5 – 6, or IIS 7.x and later in Classic mode (IIS 6 compatibility mode).  The handlers element is used on sites running on IIS 7.x and later (Integrated mode).

@2017-01-18 12:48:38

HttpApplication is responsible for hooking up and executing HttpHandlers and HttpModules which typically is done declaratively in web.config. Modules can also be added dynamically in code very early in the pipeline process. ASP.NET internally uses some very complex logic to find modules and handlers from various locations and hooks them up to new HttpApplication instances and finally manages the execution via StepManager.

@2017-01-18 12:53:56

HTTP Modules

Modules are called before and after the handler executes. Modules enable developers to intercept, participate in, or modify each individual request. Modules implement the IHttpModule interface, which is located in the System.Web namespace.

Available Events

An HttpApplication class provides a number of events with which modules can synchronize. The following events are available for modules to synchronize with on each request. These events are listed in sequential order:

  • BeginRequest: Request has been started. If you need to do something at the beginning of a request (for example, display advertisement banners at the top of each page), synchronize this event.
  • AuthenticateRequest: If you want to plug in your own custom authentication scheme (for example, look up a user against a database to validate the password), build a module that synchronizes this event and authenticates the user how you want to.
  • AuthorizeRequest: This event is used internally to implement authorization mechanisms (for example, to store your access control lists (ACLs) in a database rather than in the file system). Although you can override this event, there are not many good reasons to do so.
  • ResolveRequestCache: This event determines if a page can be 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 output back to the Output cache. If you are building a custom cache module, you write the output back to your cache.
  • EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information to the page.

The following events are available for modules to synchronize with for each request transmission. The order of these events is non-deterministic.

  • PreSendRequestHeaders: This event occurs before the headers are sent. If you want to add additional headers, you can synchronize this event from a custom module.
  • PreSendRequestContent: This event occurs when the Response.Flush method is called. If you want to add additional content, you can synchronize this event from a custom module.
  • Error: This event occurs when an unhandled exception occurs. If you want to write a custom error handler module, synchronize this event.

The following example demonstrates how to create a custom HTTP module and connect the AcquireRequestState event to the HTTP module. HTTP modules intercept each request to Web application resources, thereby allowing you to filter client requests. Any HTTP module that subscribes to an HttpApplication event must implement the IHttpModule interface.

 
using System;
using System.Web;

namespace Samples.AspNet.CS
{
    public class CustomHTTPModule : IHttpModule
    {
        public CustomHTTPModule()
        {
            // Class constructor.
        }

        // Classes that inherit IHttpModule 
        // must implement the Init and Dispose methods.
        public void Init(HttpApplication app)
        {

            app.AcquireRequestState += new EventHandler(app_AcquireRequestState);
	    app.PostAcquireRequestState += new EventHandler(app_PostAcquireRequestState);
	}

        public void Dispose()
        {
            // Add code to clean up the
            // instance variables of a module.
        }

        // Define a custom AcquireRequestState event handler.
        public void app_AcquireRequestState(object o, EventArgs ea)
        {
            HttpApplication httpApp = (HttpApplication)o;
            HttpContext ctx = HttpContext.Current;
            ctx.Response.Write(" Executing AcquireRequestState ");
        }

        // Define a custom PostAcquireRequestState event handler.
		public void app_PostAcquireRequestState(object o, EventArgs ea)
		{
			HttpApplication httpApp = (HttpApplication)o;
			HttpContext ctx = HttpContext.Current;
			ctx.Response.Write(" Executing PostAcquireRequestState ");
		}

	}
}

Before an event in a custom HTTP module can occur, you must modify the configuration settings in the Web.config file to notify ASP.NET about the HTTP module. The following example shows the appropriate configuration setting in the httpModules section of the Web.config file. The following setting applies to IIS 7.0 Classic mode and to earlier versions of IIS.

<configuration>
  <system.web>
    <httpModules>
      <add type="Samples.AspNet.CS.CustomHTTPModule"
        name="CustomHttpModule" />
      </httpModules>
  </system.web>
</configuration>

The following setting applies to IIS 7.0 Integrated mode.

<configuration>
  <system.webServer>
    <modules>
      <add type="Samples.AspNet.CS.CustomHTTPModule"
        name="CustomHttpModule" />
      </modules>
  </system.webServer>
</configuration>

 

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com