1

(免责声明:MVC 新手)

我正在尝试设置一个网站产品列表,其中包含允许用户按产品文件夹/产品名称和产品文件夹/类别/产品名称请求页面的类别。那可能吗?

我最接近的是将以下内容添加到 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 });
4

1 回答 1

3

您需要先按最具体的路线对路线进行排序。

我猜您的 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 });
于 2013-08-09T20:48:52.153 回答