Pages

Men

rh

7/01/2012

HTTP Handlers

HTTP Handlers

HTTP handlers are simply classes that implement the IHttpHandler interface, as shown in the following lines of code: 

   interface IHttpHandler
{
  // called to process request and generate response
  void ProcessRequest(HttpContext ctx);
  // called to see if handler can be pooled
  bool IsReuseable { get; }
}
 
 
Handlers can also implement the IHttpAsyncHandler interface if they want to support asynchronous invocation.
The ProcessRequest method is called by an HttpApplication object when it wants the handler to process the current HTTP request and to generate a response. The IsReuseable property is accessed in order to determine whether a handler can be used more than once.

The code in Figure 4 implements a simple reusable HTTP handler that responds to all requests by returning the current time in an XML tag. You should note the use of the HttpContext object's Response property to set the response message's MIME type and to write out its content.
Once an HTTP handler class is implemented, it must be deployed. Deployment involves three steps. First, you have to put the compiled code someplace where the ASP.NET worker process can find it. In general, that means you place your compiled .NET assembly (typically a DLL) in the bin subdirectory of your Web server's virtual directory or in the Global Assembly Cache (GAC).

Next, you have to tell the HTTP pipeline to execute your code when an HTTP request that meets some basic criteria arrives. You do this by adding an <httpHandlers> section to your virtual directory's Web.config file:
<configuration>
 <system.web>
  <httpHandlers>
   <add verb="GET" path="*.time"
     type="Pipeline.TimeHandler, 
     Pipeline"
   />
  </httpHandlers>
 </system.web>
</configuration>
 
 
This information is treated as an addendum to the configuration details specified in the global .NET machine.config file. In this example, the Web.config file tells the ASP.NET HTTP pipeline to process HTTP GET requests for .time files by invoking the Pipeline.TimeHandler class in the Pipeline assembly.

Finally, you have to tell IIS to route requests for .time files to the aspnet_isapi.dll library so that they can be funneled into the pipeline in the first place. This requires adding a new file mapping to the IIS metabase. The easiest way to do this is using the IIS management console, which shows a virtual directory's file extension mappings on the Mappings tab of the Application Configuration dialog (see Figure 5).

No comments :

Post a Comment