Geeks With Blogs
Sankarsan Bose .NET Diaries

In my last post I had discussed about the key classes/interfaces involved in the ASP.NET MVC routing process.In this post we will develop sample route handler.To implement a route handler we need to implement the System.Web.Routing.IRouteHandler interface.The GetHttpHandler method of this interface should create the instance of IHttpHandler which in turn has to create the controller instance.Let us concentrate on this IHttpHandler implementation first.Take a close look at the code below:

public class CustomMVCHandler:IHttpHandler

      public RequestContext RequestContext { get; set; }

      public CustomMVCHandler(RequestContext requestContext)
          this.RequestContext = requestContext;


      #region IHttpHandler Members


So this class implements IHttpHandler and you need pass the System.Web.Routing.RequestContext to instantiate it.The ProcessRequest methods does the following:

  1. Get the controller identifier from RouteData stored in the RequestContext.
  2. Invokes the CreateController method of ControllerFactory to create an controller instance.
  3. Invokes the execute method of the controller. The code sample is shown below:

void IHttpHandler.ProcessRequest(HttpContext context)
       string controllerId = RequestContext.RouteData.GetRequiredString("controllerId");
       IController controller = null;
       IControllerFactory factory = null;
           factory = ControllerBuilder.Current.GetControllerFactory();
           controller = factory.CreateController(RequestContext, controllerId);
           if (controller != null)

Now the RouteHandler just instantiates this MVCHandler by passing the RequestContext as shown below:

public class CustomRouteHandler:IRouteHandler
       #region IRouteHandler Members

       public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext)
          return  new CustomMVCHandler(requestContext);


Now we have plug in this route handler into the ASP.NET MVC application by creating a new route object in Application_Start event of global.asax.cs as shown below:

public static void RegisterRoutes(RouteCollection routes)
      RouteValueDictionary defaults = new RouteValueDictionary();
      defaults.Add("controllerId", "Home");
     Route customRoute = new Route("{controllerId}/{action}/{id}",defaults, new SB.Web.Mvc.CustomRouteHandler());

So our sample route handler is now up and running.

Posted on Sunday, January 18, 2009 12:48 AM ASP.NET MVC | Back to top

Comments on this post: Developing Custom RouteHandler

# re: Developing Custom RouteHandler
Requesting Gravatar...
This is nice post
how to use this for hiding controller name from the URL
Left by Harshil Gandhi on Sep 21, 2012 7:10 AM

Your comment:
 (will show your gravatar)

Copyright © sankarsan | Powered by: