【问题标题】:Is it possible to have multiple MVC routes point to the same controller/view?是否可以让多个 MVC 路由指向同一个控制器/视图?
【发布时间】:2013-08-11 21:32:03
【问题描述】:

(免责声明: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 });

【问题讨论】:

  • 您需要先按最具体的路线排列路线。
  • 罗伯特的评论就是答案。与 CategoryOneProducts 交换产品路线
  • 现在我不太确定这是否可能,stackoverflow.com/a/6226639/832705 问题答案指出您不能期望 MVC 处理能够区分控制器和操作
  • 应该工作...
  • @stackuser83 - 对该帖子的评论是关于“/foo” “/bar” 在没有额外限制的情况下无法区分(即,如果您只有 2 条路线 "{foo}""{bar}")。

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


【解决方案1】:

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

我猜你的 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 });

【讨论】:

  • 将 url:"Products/CategoryOne/{action}/{id} 路由放在 url:"Products/{action}/{id}" 路由之前似乎会导致自动替换 "Product/" 的标签 href 被 "Product/CategoryOne" 替换,有什么方法可以避免这种情况吗?
  • @stackuser83 - 您可以为大多数助手指定路由名称...但是您确实应该停下来考虑从 url 数据到操作以及从路由数据到要创建的路由的映射。您可能会发现其他一些 Url 结构(或路由结构)不那么令人困惑。
  • @AlexeiLevenkov 这对帮助程序很有帮助,我不认为 Razor 会生成链接 URL,它们是静态文本,仍然被路由替换或作为前缀。我试图让网站用户的事情变得更简单,但最终却陷入了复杂的路线表达领域
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多