是否可以让多个MVC路由指向同一个控制器/视图?

时间:2013-08-09 20:44:47

标签: c# asp.net-mvc asp.net-mvc-4 visual-studio-2012

(免责声明:MVC新手)

我正在尝试设置一个网站产品列表,其中的类别允许用户通过productfolder / productname和productfolder / category / productname请求页面。这可能吗?

我最接近的是将以下内容添加到RouteConfig.cs RegisterRoutes方法中,并将ProductNameOne.cshtml放在Views \ Products解决方案文件夹中。这导致能够看到'... / Products / Index'和'... / Products / ProductNameOne'页面,但'... / Products / CategoryOne / ProductNameOne'返回404

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(name: "Products", url: "Products/{action}/{id}",
            defaults: new { controller = "Products", action = "Index", id = 
            UrlParameter.Optional });


routes.MapRoute(name: "CategoryOneProducts", url: "Products/CategoryOne/{action}/{id}",
            defaults: new { controller = "Products", action = "ProductNameOne", id = 
            UrlParameter.Optional });

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

1 个答案:

答案 0 :(得分:2)

您需要先通过最具体的路线订购路线。

我猜你的404网址与第一条路线匹配,然后爆炸,因为CategoryOne不存在作为ID。

重新排列路线,以便首先尝试CategoryOne路线:

routes.MapRoute(name: "CategoryOneProducts", url: "Products/CategoryOne/{action}/{id}",
        defaults: new { controller = "Products", action = "ProductNameOne", id = 
        UrlParameter.Optional });

routes.MapRoute(name: "Products", url: "Products/{action}/{id}",
        defaults: new { controller = "Products", action = "Index", id = 
        UrlParameter.Optional });