Click here to Skip to main content
15,870,130 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET 4.0 HttpHandler Routing Support

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
24 Oct 2011CPOL 28.2K   7  
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)


Written By
Architect
Switzerland Switzerland
Senior IT Consultant working in Switzerland as Senior Software Engineer.

Find more at on my blog.

Comments and Discussions

 
-- There are no messages in this forum --