HTTP Handlers and Factories
ASP.NET provides a low-level request/response API that enables developers to use
.NET Framework classes to service incoming HTTP requests. Developers accomplish
this by authoring classes that support the System.Web.IHTTPHandler interface
and implement the ProcessRequest() method. Handlers are often useful when
the services provided by the high-level page framework abstraction are not required
for processing the HTTP request. Common uses of handlers include filters and
CGI-like applications, especially those that return binary data.
Each incoming HTTP request received by ASP.NET is ultimately processed by a specific
instance of a class that implements IHTTPHandler. IHttpHandlerFactory provides the infrastructure
that handles the actual resolution of URL requests to IHttpHandler instances.
In addition to the default IHttpHandlerFactory classes provided by ASP.NET, developers can optionally create and register
factories to support rich request resolution and activation scenarios.
Configuring HTTP Handlers and Factories
HTTP handlers and factories are declared in the ASP.NET configuration as part
of a web.config file. ASP.NET defines an <httphandlers> configuration section
where handlers and factories can be added and removed. Settings for
HttpHandlerFactory and HttpHandler are inherited by subdirectories.
For example, ASP.NET maps all requests for .aspx files to the PageHandlerFactory class in
the global machine.config file:
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory,System.Web" />
Creating a Custom HTTP Handler
The following sample creates a custom HttpHandler that handles
all requests to "SimpleHandler.axd".
VB Simple HttpHandler
A custom HTTP handler can be created by implementing the IHttpHandler
interface, which contains only two methods. By calling IsReusable, an
HTTP factory can query a handler to determine whether the same instance can be used to service multiple requests. The
ProcessRequest method takes an HttpContext instance as a parameter, which
gives it access to the Request and Response intrinsics.
In the following sample, request data is ignored and a constant
string is sent as a response to the client.
Public Class SimpleHandler : Inherits IHttpHandler
Public Sub ProcessRequest(context As HttpContext)
Public Function IsReusable() As Boolean
After placing the handler class definition in the application's \App_Code directory,
the handler class can be specified as a target for requests. In this case, all
requests for "SimpleHandler.axd" will be routed to an instance of the
SimpleHandler class, which lives in the namespace
<add verb="*" path="SimpleHandler.axd" type="Acme.SimpleHandler" />