Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

asp.net mvc complex routing for tree path

I am wondering how can I define a routing map like this:

{TreePath}/{Action}{Id} 

TreeMap is dynamically loaded from a database like this:

 'Gallery/GalleryA/SubGalleryA/View/3'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('/');
            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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...