自定义路由 - 从URL删除控制器和操作

时间:2011-06-26 15:03:56

标签: model-view-controller routing url-routing

我在删除控制器和操作时没有干扰默认路由的URL?  例如:

自: http://mysite.com/departaments/products/footwear/male其中部门=控制器,行动=产品和鞋类,男性=参数

要: http://mysite.com/footwear/male

所以我在自定义路线示例中采取控制器和操作:

        routes.MapRoute
        (
            "Products",
            "{p0}/{p1}/{p2}/{p3}/{p4}/{p5}",
            new
            {
                controller = "Departaments",
                action = "Products",
                p0 = "",
                p1 = "",
                p2 = "",
                p3 = "",
                p4 = "",
                p5 = ""
            },
            new String[]
            {
                "MvcApplication1.Controllers"
            }
        );


        routes.MapRoute
        (
            "Default",
            "{controller}/{action}/{p0}",
            new
            {
                controller = "Home",
                action = "Index",
                p0 = ""
            },
            new String[]
            {
                "MvcApplication1.Controllers"
            }
        );

1 个答案:

答案 0 :(得分:0)

您必须在默认路由后添加Products路由,否则Products路由将始终匹配六个或更少的任何URL。这可能会引入一个新问题,默认路由将匹配三个或更少段的任何URL,除非您使用所有控制器名称向控制器令牌添加约束,例如, controller = @"home|account|departments"MvcCodeRouting库可以自动注册非常严格的路由(使用控制器和操作的约束),然后您也可以添加自己的路由,而不必担心冲突。


routes.MapRoute("Default", "{controller}/{action}/{p0}",
   new { controller = "Home", Action = "Index", p0 = "" },
   new { controller = @"Home|Account" }, // Register controllers here
   new[] { "MvcApplication1.Controllers" });

routes.MapRoute("Products", "{p0}/{p1}/{p2}/{p3}/{p4}/{p5}",
   new { controller = "Departaments", Action = "Products", p0 = "", p1 = "", p2 = "", p3 = "", p4 = "", p5 = "" },
   new[] { "MvcApplication1.Controllers" });