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

本文关键字:同一个 控制器 视图 路由 MVC 是否 | 更新日期: 2023-09-27 18:27:09

(免责声明:MVC新手)

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

到目前为止,我最接近的是将以下内容添加到RouteConfig.cs RegisterRoutes方法中,并将ProductNameOne.cshtml放置在Views''Products解决方案文件夹中。这样就可以看到"/产品/索引"answers"/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 });

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

您需要首先通过最特定的路线来订购路线

我猜你的404 URL与第一条路由匹配,然后因为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 });