Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

ASP.NET 4.0 HttpHandler Routing Support

5.00/5 (3 votes)
24 Oct 2011CPOL 28.6K  
Adding support for IHttpHandler on ASP.NET Routing

I'm a big fan of ASP.NET Routing and I use it a lot on my ASP.NET Webforms applications.


If you're just getting started with Routing on ASP.NET Webforms, I recommend reading this post from Scott Guthrie.


Ok now, back to the subject, one thing about Routing is that it doesn't support routes that point to HttpHandlers (common .ASHX files).



The code below comes just to overcome this limitation by adding a new method (and one overload) to the RoutesCollection object that will let you map a route to an *.ashx URL or directly to the handler object.

The Code


namespace System.Web.Routing
{
 public class HttpHandlerRoute : IRouteHandler
 {
  private String _virtualPath = null;
  private IHttpHandler _handler = null;

  public HttpHandlerRoute(String virtualPath)
  {
   _virtualPath = virtualPath;
  }

  public HttpHandlerRoute(IHttpHandler handler)
  {
   _handler = handler;
  }

  public IHttpHandler GetHttpHandler(RequestContext requestContext)
  {
   IHttpHandler result;
   if (_handler == null)
   {
    result = (IHttpHandler)System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(IHttpHandler));
   }
   else
   {
    result = _handler;
   }
   return result;
  }
 }

 public static class RoutingExtensions
 {
  public static void MapHttpHandlerRoute(this RouteCollection routes, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults = null, RouteValueDictionary constraints = null)
  {
   var route = new Route(routeUrl, defaults, constraints, new HttpHandlerRoute(physicalFile));
   RouteTable.Routes.Add(routeName, route);
  }

  public static void MapHttpHandlerRoute(this RouteCollection routes, string routeName, string routeUrl, IHttpHandler handler, RouteValueDictionary defaults = null, RouteValueDictionary constraints = null)
  {
   var route = new Route(routeUrl, defaults, constraints, new HttpHandlerRoute(handler));
   RouteTable.Routes.Add(routeName, route);
  }
 }
}


How to use it


// using the handler url
routes.MapHttpHandlerRoute("MyControllerName", "Controllers/MyController", "~/mycontroller.ashx");

// using an instance of the handler
routes.MapHttpHandlerRoute("MyControllerName", "Controllers/MyController", new mycontroller());


And that's it! :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)