【问题标题】:MVC Routing problem, 404 and unmatched routesMVC 路由问题,404 和不匹配的路由
【发布时间】:2011-10-25 07:03:00
【问题描述】:

我正在尝试在 MVC3 中设置与旧版 (SP 2007) 系统匹配的路由方案。这些是我设置的路线:

routes.MapRoute("administration", 
    "Administration/{action}/{id}", 
    new { controller = "Administration", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("workOrderSearch", 
    "WorkOrderSearch", 
    new {controller = "Home", action = "WorkOrderSearch"});
routes.MapRoute("customers",
    "{customerNumber}/{action}", 
    new {controller = "customer", action = "Index"}, 
    new {customerNumber = @"\d*"});
routes.MapRoute("graphicNames",
    "{customerNumber}/{graphicNameId}/{action}/{id}", 
    new {controller="GraphicName", action="Index", id=UrlParameter.Optional}, 
    new {customerNumber = @"\d*",graphicNameId = @"\d*", action=@"\w*"});
routes.MapRoute("workOrders", 
    "{customerNumber}/{graphicNameId}/{graphicNumber}/WorkOrder/{action}/{id}", 
    new { controller = "WorkOrder", action = "Index", id = UrlParameter.Optional }, 
    new { graphicNameId = @"\d*", graphicNumber = @"\d*-\d*" });
routes.MapRoute("graphics", 
    "{customerNumber}/{graphicNameId}/{graphicNumber}/{action}", 
    new { controller = "Graphic", action = "Index", id = UrlParameter.Optional }, 
    new { graphicNameId = @"\d*", graphicNumber = @"\d*-\d*" });

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

它大多工作得很好。但是,当尝试使用“graphicNames”路线时,我遇到了问题。如果我使用这个网址:

http://localhost:1234/1234/321/Index

它工作正常,我得到了 GraphicName 控制器上的 Index 操作。但是,如果我这样做:

http://localhost:1234/1234/321

我得到一个 404。

所有其他路线似乎都按预期工作。

编辑:解决方案是向客户的路线添加一个约束,以便操作仅是 'action=@"[A-Za-z]*"

【问题讨论】:

  • 在请求中添加一个斜杠......它有效吗?
  • 不,末尾的斜杠没有帮助。

标签: asp.net-mvc-3 asp.net-mvc-routing


【解决方案1】:

你有:

routes.MapRoute("graphicNames",
"{customerNumber}/{graphicNameId}/{action}/{id}", 
new {controller="GraphicName", action="Index", id=UrlParameter.Optional}, 
new {customerNumber = @"\d*",graphicNameId = @"\d*", action=@"\w*"});

但是在此之前你有

routes.MapRoute("customers",
"{customerNumber}/{action}", 
new {controller = "customer", action = "Index"}, 
new {customerNumber = @"\d*"});

基于您的网址,只有两个参数 /1234/321 将首先匹配客户路线。要么添加一个动作必须是 alpha 的路由约束,要么将它移到你的 graphicsNames 路由下面,因为顺序在路由匹配中非常很重要。

【讨论】:

  • 我看不出我有两个可选参数。 Action 有一个默认值,id 是可选的。你是说 customerNumber 和 graphicsNameId 是可选的吗?
  • 哦。深夜。我想我应该说“失踪”不是可选的。我相信解析器在匹配参数时遇到问题。尝试为 graphicsNameId=0 或 graphicsNameId="" 指定默认值,看看是否有任何变化。
  • 很遗憾,这没有帮助。
  • 已在上面编辑 - 我认为您的客户路线与此语法匹配。您只有两个参数,我认为它认为您的“321”是您的客户路线“Action”参数。您需要将该路由向下移动到另一个路由下方,或者在路由约束中指定它必须是 alpha。
  • 好收获!我实际上已经对客户的操作添加了一个约束,但是我愚蠢地使用了“\w*”,它仍然会匹配“123”。我添加了这个:action=@"[A-Za-z]*" 一切似乎都很好。谢谢!
猜你喜欢
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
  • 2018-11-01
  • 2016-11-09
  • 2011-06-16
  • 1970-01-01
相关资源
最近更新 更多