Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
  • 💬 Discuss

Dynamic Handler Assignment

In some cases, you may want to dynamically determine at runtime the appropriate HttpHandler to call for handling a particular request. .NET provides a Factory design pattern that allows you to create a Factory that is responsible for creating the appropriate HttpHandler to deal with the request. This gives you some additional flexibility in creating HttpHandlers. You could look inside an associated file to determine which handler should be called.

The Factory pattern also provides a way for you to potentially pre-create a number of handlers and hand them to ASP.NET when it requests one, without the overhead of creating one each and every time.

Let's look at an example. Listing 8.17 shows a class that implements IHttpHandlerFactory. This class looks for an argument passed as part of the URL. If the value of this argument is "Chris", the ChrisHandler is returned to ASP.NET to handle the request. If the value of the argument is "Jeffrey", the JeffreyHandler is returned.

Listing 8.17—A Sample HttpHandlerFactory That Returns Different Handlers Based on the name Parameter

using System;
using System.Web;
using System.Web.UI;

namespace Handlers
{
  /// <summary>
  /// Summary description for HandlerFactory.
  /// </summary>
  public class HandlerFactory : IHttpHandlerFactory
  {
    public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string 
pathTranslated)
    {

      // Check the name property 
      if(context.Request["Name"] == "Chris")
        // If it's Chris return chris
        return new ChrisHandler();
      else
        // Else return Jeff
        return new JeffHandler();
    }

    // required to implement the interface
    public void ReleaseHandler(IHttpHandler handler) 
    {
    }
  }

  /// The ChrisHandler
  /// 
  public class ChrisHandler : IHttpHandler
  {
    public void ProcessRequest(HttpContext context)
    {
      context.Response.Write("<html><body>Chris</body></html>");
    }

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

  /// The JeffHandler
  /// 
  public class JeffHandler : IHttpHandler
  {
    public void ProcessRequest(HttpContext context)
    {
      context.Response.Write("<html><body>Jeff</body></html>");
    }

    public bool IsReusable
    {
      get
      {
        return true;
      }
    }

  }

}

The Chris and Jeffrey handlers just write a simple document with the name Jeffrey or Chris. The HttpHandlerFactory is hooked up in Web.Config the same way an ordinary HttpHandler is hooked up.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus