Share via

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.

using System;
using System.Web;

namespace Handlers
    class HandlerFactory : IHttpHandlerFactory
        public IHttpHandler GetHandler(HttpContext context, string requestType, String url, String pathTranslated)
            IHttpHandler handlerToReturn;
            if("get" == context.Request.RequestType.ToLower())
                handlerToReturn = new SynchHandler();
            else if("post" == context.Request.RequestType.ToLower())
                handlerToReturn = new AsynchHandler();
                handlerToReturn = null;
            return handlerToReturn;
        public void ReleaseHandler(IHttpHandler handler)
        public bool IsReusable
                // To enable pooling, return true here.
                // This keeps the handler in memory.
                return false;

[Visual Basic]
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()
                If "post" = context.Request.RequestType.ToLower() Then
                    handlerToReturn = New AsynchHandler()
                    handlerToReturn = Nothing
                End If
            End If
            Return handlerToReturn
        End Function

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

        Public ReadOnly Property IsReusable() As Boolean
                ' 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:

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

See Also

HttpHandlers | Creating HttpHandlers