通过创建实现 IHttpHandlerFactory 接口的类,可以为每个 HTTP 请求生成新的处理程序实例。在下面的示例中,将用一个 HttpHandler 工厂为 HTTP GET 请求和 HTTP POST 请求创建不同的处理程序。其中一个处理程序是上面示例中的同步处理程序的实例;另一个处理程序则是异步处理程序示例的实例。
[C#] 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(); } else { handlerToReturn = null; } return handlerToReturn; } public void ReleaseHandler(IHttpHandler handler) { } public bool IsReusable { get { // 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() Else If "post" = context.Request.RequestType.ToLower() Then handlerToReturn = New AsynchHandler() Else 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 Get ' To enable pooling, return true here. ' This keeps the handler in memory. Return False End Get End Property End Class End Namespace
通过在 Web.config 中创建项来注册自定义 HttpHandler 工厂,如下所示:
<configuration> <system.web> <httpHandlers> <add verb="GET,POST" path="*.MyFactory" type="Handlers.HandlerFactory, Handlers" /> </httpHandlers> </system.web> </configuration>