Compartir a través de


IHttpHandlerFactory.GetHandler(HttpContext, String, String, String) Método

Definición

Devuelve una instancia de una clase que implementa la interfaz IHttpHandler.

public:
 System::Web::IHttpHandler ^ GetHandler(System::Web::HttpContext ^ context, System::String ^ requestType, System::String ^ url, System::String ^ pathTranslated);
public System.Web.IHttpHandler GetHandler (System.Web.HttpContext context, string requestType, string url, string pathTranslated);
abstract member GetHandler : System.Web.HttpContext * string * string * string -> System.Web.IHttpHandler
Public Function GetHandler (context As HttpContext, requestType As String, url As String, pathTranslated As String) As IHttpHandler

Parámetros

context
HttpContext

Instancia de la clase HttpContext que proporciona referencias a objetos de servidor intrínsecos (por ejemplo, Request, Response, Session y Server) utilizados para atender las solicitudes HTTP.

requestType
String

Método de transferencia de datos HTTP (GET o POST) que utiliza el cliente.

url
String

RawUrl del recurso solicitado.

pathTranslated
String

PhysicalApplicationPath del recurso solicitado.

Devoluciones

IHttpHandler

Nuevo objeto IHttpHandler que procesa la solicitud.

Ejemplos

En el ejemplo de código siguiente se muestra cómo crear objetos de controlador personalizados en respuesta a una solicitud de cliente. El ejemplo tiene dos partes:

  • Una clase de generador de controladores.

  • Extracto de archivo Web.config.

La primera parte del ejemplo muestra cómo crear objetos de controlador personalizados en respuesta a una solicitud de cliente para una página denominada abc.aspx o xyz.aspx. La clase de generador de controladores denominada hwf crea el objeto de controlador adecuado en función de la página solicitada.

// Name this C# file HandlerFactoryTest.cs and compile it with the
// command line: csc /t:Library /r:System.Web.dll HandlerFactoryTest.cs.
// Copy HandlerFactoryTest.dll to your \bin directory.

namespace test
{
   using System;
   using System.Web;

   // Factory class that creates a handler object based on a request
   // for either abc.aspx or xyz.aspx as specified in the Web.config file.
   public class MyFactory : IHttpHandlerFactory
   {
      [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
      public virtual IHttpHandler GetHandler(HttpContext context,
                                             String requestType,
                                             String url,
                                             String pathTranslated)
      {
         String fname = url.Substring(url.LastIndexOf('/')+1);
         String cname = fname.Substring(0, fname.IndexOf('.'));
         String className = "test." + cname;

         Object h = null;

         // Try to create the handler object.
         try
         {
            // Create the handler by calling class abc or class xyz.
            h = Activator.CreateInstance(Type.GetType(className));
         }
         catch(Exception e)
         {
            throw new HttpException("Factory couldn't create instance " +
                                    "of type " + className, e);
         }
         return (IHttpHandler)h;
      }

      // This is a must override method.
      public virtual void ReleaseHandler(IHttpHandler handler)
      {
      }
   }

   // Class definition for abc.aspx handler.
   public class abc : IHttpHandler
   {
      public virtual void ProcessRequest(HttpContext context)
      {
         context.Response.Write("<html><body>");
         context.Response.Write("<p>ABC Handler</p>\n");
         context.Response.Write("</body></html>");
      }

      public virtual bool IsReusable
      {
         get { return true; }
      }
   }

   // Class definition for xyz.aspx handler.
   public class xyz : IHttpHandler
   {
      public virtual void ProcessRequest(HttpContext context)
      {
         context.Response.Write("<html><body>");
         context.Response.Write("<p>XYZ Handler</p>\n");
         context.Response.Write("</body></html>");
      }

      public virtual bool IsReusable
      {
         get { return true; }
      }
   }
}

/*
______________________________________________________________

To use the handler factory, use the following lines in a
Web.config file.

<configuration>
   <system.web>
      <httpHandlers>
         <add verb="*" path="abc.aspx" type="test.MyFactory,HandlerFactoryTest" />
         <add verb="*" path="xyz.aspx" type="test.MyFactory,HandlerFactoryTest" />
      </httpHandlers>
   </system.web>
</configuration>
*/
' Name this Visual Basic file HandlerFactoryTest.vb and compile it with 
' the command line: vbc /t:Library /r:System.Web.dll HandlerFactoryTest.vb.
' Copy HandlerFactoryTest.dll to your \bin directory.
Imports System.Web

Namespace test    
    
    ' Factory class that creates a handler object based on a request 
    ' for either abc.aspx or xyz.aspx as specified in the Web.config file.
    Public Class MyFactory
        Implements IHttpHandlerFactory
        
        <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
        Public Overridable Function GetHandler(context As HttpContext, _
        requestType As String, url As String, pathTranslated As String) _
        As IHttpHandler _
        Implements IHttpHandlerFactory.GetHandler
        
            Dim fname As String = url.Substring(url.LastIndexOf("/"c) + 1)
            Dim cname As String = fname.Substring(0, fname.IndexOf("."c))
            Dim className As String = "test." & cname
            
            Dim h As Object = Nothing
            
            Try ' to create the handler object.
                ' Create by calling class abc or class xyz.
                h = Activator.CreateInstance(Type.GetType(className))
            Catch e As Exception
                Throw New HttpException("Factory couldn't create instance " & _
                    "of type " & className, e)
            End Try
            Return CType(h, IHttpHandler)
        End Function
        
        
        ' This is a must override method.
        Public Overridable Sub ReleaseHandler(handler As IHttpHandler) _
        Implements IHttpHandlerFactory.ReleaseHandler
        
        End Sub
        
    End Class
    
    
    ' Class definition for abc.aspx handler.
    Public Class abc
        Implements IHttpHandler
        
        Public Overridable Sub ProcessRequest(context As HttpContext) _
        Implements IHttpHandler.ProcessRequest
        
            context.Response.Write("<html><body>")
            context.Response.Write("<p>ABC Handler</p>" & _
                Microsoft.VisualBasic.ControlChars.CrLf)
            context.Response.Write("</body></html>")
        End Sub        
        
        Public Overridable ReadOnly Property IsReusable() As Boolean _
        Implements IHttpHandler.IsReusable
        
            Get
                Return True
            End Get
        End Property
    End Class
     
    ' Class definition for xyz.aspx handler.
    Public Class xyz
        Implements IHttpHandler
        
        Public Overridable Sub ProcessRequest(context As HttpContext) _
        Implements IHttpHandler.ProcessRequest
        
            context.Response.Write("<html><body>")
            context.Response.Write("<p>XYZ Handler</p>" & _
                Microsoft.VisualBasic.ControlChars.CrLf)
            context.Response.Write("</body></html>")
        End Sub
        
        
        Public Overridable ReadOnly Property IsReusable() As Boolean _
        Implements IHttpHandler.IsReusable
        
            Get
                Return True
            End Get
        End Property
    End Class
End Namespace

'______________________________________________________________
'
'To use the handler factory, use the following lines in a
'Web.config file. (be sure to remove the comment markers)
'
'         <add verb="*" path="abc.aspx" type="test.MyFactory,HandlerFactoryTest" />
'         <add verb="*" path="xyz.aspx" type="test.MyFactory,HandlerFactoryTest" />

La segunda parte del ejemplo muestra un extracto de archivo Web.config. Para usar el generador de controladores anterior, agregue las líneas siguientes al archivo Web.config.

<configuration>   
  <system.web>   
    <httpHandlers>   
      <add verb="*" path="abc.aspx" type="test.MyFactory,HandlerFactoryTest" />   
      <add verb="*" path="xyz.aspx" type="test.MyFactory,HandlerFactoryTest" />   
    </httpHandlers>   
  </system.web>  
</configuration>   

Se aplica a