树路径的asp.net mvc复杂路由 [英] asp.net mvc complex routing for tree path

查看:31
本文介绍了树路径的asp.net mvc复杂路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何定义这样的路由映射:

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

{TreePath}/{Action}{Id} 

TreeMap 是从这样的数据库动态加载的:

TreeMap is dynamically loaded from a database like this:

 'Gallery/GalleryA/SubGalleryA/View/3'

推荐答案

您可以创建自定义路由处理程序来执行此操作.实际路线是一个包罗万象的:

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

树处理程序查看路径,提取最后一部分作为操作,然后重定向到控制器.动作部分也从路径中删除.添加 {id} 部分应该很简单.

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");
    }
}

现在你可以像/Tree/Node1/Node2/Node3/DoStuff一样调用URL.action获取的路径是Node1/Node2/Node3

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

这篇关于树路径的asp.net mvc复杂路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆