开发者

Custom Routing - Remove Controller and Action From URL

There is as I remove the controller and action without interfering with the url of the default route? For example:

From: http://mysite.com/departaments/products/footwear/male where departaments = controller, action = products and footwear and male = parameters

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

So I take the controller and action on a custom route example:

        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.Contro开发者_StackOverflow社区llers"
            }
        );


You have to add the Products route after the Default route, otherwise the Products route will always match any URL of six segments or less. This may introduce an new problem, the Default route will match any URL of three segments or less, unless you add a constraint to the controller token with all the controller names, e.g. controller = @"home|account|departments". The MvcCodeRouting library can automatically register routes that are very strict (using constraints for controller and action), then you can also add your own routes and you don't have to worry about conflicts.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜