asp.net mvc complex routing for tree path

You can create a custom route handler to do this. The actual route is a catch-all:

routes.MapRoute(
    "Tree",
    "Tree/{*path}",
    new { controller = "Tree", action = "Index" })
        .RouteHandler = new TreeRouteHandler();

The tree handler looks at path, extracts the last part as action, and then redirects to the controller. The action part is also removed from path. Adding the {id} part should be straightforward.

public class TreeRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        string path = requestContext.RouteData.Values["path"] as string;

        if (path != null)
        {
            int idx = path.LastIndexOf("https://stackoverflow.com/");
            if (idx >= 0)
            {
                string actionName = path.Substring(idx+1);
                if (actionName.Length > 0)
                {
                    requestContext.RouteData.Values["action"] = actionName;
                    requestContext.RouteData.Values["path"] = 
                        path.Substring(0, idx);
                }
            }
        }

        return new MvcHandler(requestContext);
    }
}

Your controller then works as you would expect it:

public class TreeController : Controller
{
    public ActionResult DoStuff(string path)
    {
        ViewData["path"] = path;
        return View("Index");
    }
}

Now you can call URL like /Tree/Node1/Node2/Node3/DoStuff. The path that the action gets is Node1/Node2/Node3

Leave a Comment