Vous êtes sur la page 1sur 8

DAY 14 TASKS

HttpHandlers

HttpHandlers are classes that implement the IHttpHandler and IHttpAsyncHandler interfaces. This section

describes how to create and register HttpHandlers and provides examples of a synchronous handler, an

asynchronous handler, and a handler factory.

1. ASP.NET Request Processing

ASP.NET maps HTTP requests to HttpHandlers. Each HttpHandler enables processing of individual HTTP

URLs or groups of URL extensions within an application. HttpHandlers have the same functionality as

ISAPI extensions with a much simpler programming model. The following table shows examples of the

HttpHandlers provided by ASP.NET.

Handler Description

ASP.NET Page Handler (*.aspx) The default HttpHandler for all ASP.NET pages.

ASP.NET Service Handler (*.asmx) The default HttpHandler for all ASP.NET service pages.

An HttpHandler can be either synchronous or asynchronous. A synchronous handler does not return until it

finishes processing the HTTP request for which it is called. An asynchronous handler usually launches a

process that can be lengthy, and returns before that process finishes.

After writing and compiling the code to implement an HttpHandler, you must register the handler using

your application's Web.config file.

Creating HttpHandlers

A synchronous HttpHandler implements the System.Web.IHttpHandler interface. An asynchronous

HttpHandler implements the System.Web.IHttpAsyncHandler interface.

The System.Web.IHttpAsyncHandler interface inherits from System.Web.IHttpHandler. Both of

these interfaces require you to implement the ProcessRequest method and the IsReusable property.

ProcessRequest processes individual HTTP requests. IsReusable specifies whether pooling is supported.

In addition, the System.Web.IHttpAsyncHandler interface requires the implementation of the

BeginProcessRequest and EndProcessRequest methods. BeginProcessRequest initiates an asynchronous

call to process individual HTTP requests, and EndProcessRequest executes cleanup code when the

process ends.

It is also possible to create an instance of an HttpHandler by means of a class implementing the

IHttpHandlerFactory interface. This can allow finer control over the processing of an HTTP request by

mapping a URL to an HttpHandler factory that creates different handlers based on a complex set of

1
conditions. For example, with an HttpHandler factory you can create one HttpHandler for a file type if the

HTTP request method is PUT, and another if the method is GET.

After you have created a custom HttpHandler you must configure ASP.NET to map incoming HTTP

requests for specific URLs to your handler. The following procedure describes the steps required.

To register an HttpHandler

1. Compile and deploy the .NET class for the HttpHandler in the \bin directory under the
application's virtual root.

2. Register the HttpHandler, synchronous or asynchronous, in the application's Web.config


configuration file. The following example maps all HTTP requests to the classes MyHandler.New and
MyHandler.Fin in the assembly MyHandler that is in the file Myhandler.dll.

3. <configuration>
4. <system.web>
5. <httpHandlers>
6. <add verb="*" path="MyHandler.New"
7. type="MyHandler.New, MyHandlerAssembly" />
8. <add verb="*" path="*.myNewFileNameExtension"
9. type="MyHandler.Fin, MyHandlerAssembly" />
10. </httpHandlers>
11. <system.web>
</configuration>

Entries within the <httpHandlers> configuration section have three attributes, as shown in the

following table.

Attribute Description

Path The path attribute can contain either a single URL path or a simple wildcard
string (for example, *.aspx).

Type Specifies a comma-separated class/assembly combination. ASP.NET


searches for the assembly DLL first in the application's private \bin directory
and then in the system assembly cache.

Verb The verb list can be either a comma-separated list of HTTP methods (for
example, "GET, PUT, POST") or a start-script mapping (for example, the
wildcard character * [an asterisk]).

2
12. Ensure that the HttpHandler file name extension is registered within Internet
Information Services (IIS).

Configuring the HttpHandler in IIS


After you develop an HttpHandler or HttpModule you must configure IIS and ASP.NET for the new code to take
effect. There are actually two steps involved in running a custom HttpHandler. First, you use the IIS Application
Configuration dialog to map the file extension to the ASP.NET engine. Second, you modify the configuration
sections in the application's web.config file to specify the namespace and class you want to use to handle that
extension.

For IIS, you add the required file extension in the AppMapping tab of Application Configuration dialog. You can
add or remove handlers using this dialog.

The dialog associates a specific file extension with a specific handler—in this case, tell IIS to use the ASP.NET
engine (aspnet_isapi.dll). Set the Executable field to the location of the aspnet_isapi.dll file on your server (your
path may vary from the path shown in the figure). Fill in the Extension field with .myext .

HttpHandler Task 1, 2 & 3

This section provides the following code examples:

1. Synchronous HttpHandler

2. Asynchronous HttpHandler

3. HttpHandler Factory

Synchronous HttpHandler

The following code demonstrates how to process requests for the specific MyApp.MyHello URL within an

ASP.NET application. Next, the configuration file changes required to register the HttpHandler are shown.
HelloWorldHandler.vb
---------------------------------------------------------------------------------------
Imports System.Web

Public Class HelloWorldHandler


Implements IHttpHandler

Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements


System.Web.IHttpHandler.ProcessRequest
Dim request As HttpRequest = context.Request
Dim response As HttpResponse = context.Response
' A file named ending in .MyHello need not exist. This handler
' executes whenever a file ending in .MyHello is requested.
response.Write("<html>")
response.Write("<body>")
response.Write("<h1> Hello from Synchronous custom handler. </h1>")
response.Write("</body>")
response.Write("</html>")
End Sub

3
Public ReadOnly Property IsReusable() As Boolean Implements
System.Web.IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Register your custom HttpHandler by creating an entry in Web.config as follows:


<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.MyHello"
type="HelloWorldHandler,httpruntime" />
</httpHandlers>
</system.web>
</configuration>

Asynchronous HttpHandler

The following code demonstrates how to register and process requests for the specific *.MyAsynch URL

within an ASP.NET application. In this case, the handler launches a time-consuming process, sending a

response to the user at several points to indicate progress. Next, the configuration file changes required to

register the HttpHandler are shown.


[Class AsynchHandler.vb]

------------------------------------------------------------------------------------------------------------------------------------------

Imports System
Imports System.Web
Imports System.Threading

Namespace handler

Public Class AsynchHandler


Implements IHttpAsyncHandler

Private _context As HttpContext


Public ReadOnly Property IsReusable() As Boolean Implements
System.Web.IHttpAsyncHandler.IsReusable
Get
Return False
End Get
End Property

4
Public Function BeginProcessRequest(ByVal context As System.Web.HttpContext,
ByVal cb As System.AsyncCallback, ByVal extraData As Object) As System.IAsyncResult
Implements System.Web.IHttpAsyncHandler.BeginProcessRequest
Dim asynch As New MyAsynchOperation(cb, context)
asynch.KickOffThread()

context.Response.Write("BeginProcessRequest. Just kicked off a Thread.<br>")


context.Response.Flush()
' Signal the application that asynchronous
' processing is being performed.
Dim asynchForBegin As New SomeResult()

' Processing is not synchronous.


asynchForBegin.SetSynch(False)

' Processing is not complete.


asynchForBegin.SetCompleted(False)

_context = context

Return New SomeResult()


End Function

Public Sub EndProcessRequest(ByVal result As System.IAsyncResult) Implements


System.Web.IHttpAsyncHandler.EndProcessRequest
_context.Response.Write("EndProcessRequest called.<br>")
End Sub

Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements


System.Web.IHttpAsyncHandler.ProcessRequest
' Ths is required but is not called.
End Sub
End Class

Class SomeResult
Implements IAsyncResult

Private _blnIsCompleted As Boolean = False


Private myMutex As Mutex = Nothing
Private myAsynchStateObject As Object = Nothing
Private _blnCompletedSynchronously As Boolean = False

Public Sub SetCompleted(ByVal blnTrueOrFalse As Boolean)


_blnIsCompleted = blnTrueOrFalse

5
End Sub

Public Sub SetSynch(ByVal blnTrueOrFalse As Boolean)


_blnCompletedSynchronously = blnTrueOrFalse
End Sub

Public ReadOnly Property AsyncState() As Object Implements


System.IAsyncResult.AsyncState
Get
Return myAsynchStateObject
End Get
End Property

Public ReadOnly Property AsyncWaitHandle() As System.Threading.WaitHandle


Implements System.IAsyncResult.AsyncWaitHandle
Get
Return myMutex
End Get
End Property

Public ReadOnly Property CompletedSynchronously() As Boolean Implements


System.IAsyncResult.CompletedSynchronously
Get
Return _blnCompletedSynchronously
End Get
End Property

Public ReadOnly Property IsCompleted() As Boolean Implements


System.IAsyncResult.IsCompleted
Get
Return _blnIsCompleted
End Get
End Property
End Class
End Namespace

Register your custom asynchronous HttpHandler by creating an entry in Web.config as follows:


<configuration>
<system.web>
<httpHandlers>
<add verb="GET,POST" path="*.MyAsynch"
type="Handlers.AsynchHandler, Handlers" />
</httpHandlers>
</system.web>
</configuration>

6
HttpHandler Factory

You can generate a new handler instance for each HTTP request by creating a class that implements the

IHttpHandlerFactory interface. In the following example, a HttpHandler factory is used to create different

handlers for an HTTP GET request and an HTTP POST request. One of the handlers is an instance of the

synchronous handler in the example above; the other handler is an instance of the asynchronous handler

example.
[Class HandlerFactory]

Imports System
Imports System.Web

Namespace Handlers
Class HandlerFactory
Implements IHttpHandlerFactory

Public Function GetHandler(ByVal context As HttpContext, ByVal requestType As


String, ByVal url As [String], ByVal pathTranslated As [String]) As IHttpHandler
Implements IHttpHandlerFactory.GetHandler
Dim handlerToReturn As IHttpHandler
If "get" = context.Request.RequestType.ToLower() Then
handlerToReturn = New SynchHandler()
Else
If "post" = context.Request.RequestType.ToLower() Then
handlerToReturn = New AsynchHandler()
Else
handlerToReturn = Nothing
End If
End If
Return handlerToReturn
End Function

7
Public Sub ReleaseHandler(ByVal handler As IHttpHandler) Implements
IHttpHandlerFactory.ReleaseHandler
End Sub

Public ReadOnly Property IsReusable() As Boolean


Get
' To enable pooling, return true here.
' This keeps the handler in memory.
Return False
End Get
End Property
End Class
End Namespace

Register your custom HttpHandler factory by creating an entry in Web.config as follows:


<configuration>
<system.web>
<httpHandlers>
<add verb="GET,POST" path="*.MyFactory"
type="Handlers.HandlerFactory, Handlers" />
</httpHandlers>
</system.web>
</configuration>

Vous aimerez peut-être aussi