【问题标题】:MVC: after adding custom route, default route is ignored?MVC:添加自定义路由后,默认路由被忽略?
【发布时间】:2014-04-23 22:15:24
【问题描述】:

在我的 routeConfig 中,我在默认路由的顶部添加了一个自定义路由

routes.MapRoute(
    name: "appointmentandattendee",
    url: "{controller}/{action}/{appointmentId}/{attendeeId}",
    defaults: new { controller = "Response", action = "Index", appointmentId = UrlParameter.Optional, attendeeId = UrlParameter.Optional }
);

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

所以,对于这个动作

public ActionResult Index(Guid appointmentId, Guid attendeeId)
{
   return Content("Hello");
}

路由看起来像

http://localhost/Response/Index/96de7851-49f6-4b69-8a58-2bea39bd466e/7d4fe8ed-7dae-e311-be8f-001c42aef0b2

但现在名称为 Default 的路由被忽略了

例如: 在我的约会控制器中,有一些动作和参数作为 id 我期待使用默认路由,但它没有 所以,对于AppointmentController中的这个动作

public ActionResult Test(Guid id)
{          
    return Content("Hello");
}

路由看起来像

localhost:/Appointment/Test?id=96de7851-49f6-4b69-8a58-2bea39bd466e

这是为什么呢? 在这种情况下不应该使用默认路由吗?

【问题讨论】:

  • 这是因为您将appointmentIdattendeeId 参数声明为可选。现在这是您路线列表中最通用的路线。您确定要它们是可选的吗?他们的目的不是总是传递给你的行动吗?
  • 即使我做了defaults: new { controller = "Response", action = "Index", appointmentId = "", attendeeId = "" } 也没有用。我最终做的是url: "Response/{appointmentId}/{attendeeId}" 所以控制器应该是响应

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing asp.net-mvc-5


【解决方案1】:

因为您的路由 appointmentandattendee 覆盖了您的默认路由。

试试这个:

routes.MapRoute(
    name: "appointmentandattendee",
    url: "Response/{action}/{appointmentId}/{attendeeId}",
    defaults: new { controller = "Response", action = "Index", appointmentId = UrlParameter.Optional, attendeeId = UrlParameter.Optional }
);

我指定 URL 的第一部分为 Response,默认控制器仍为 controller = "Response"。现在你的路线不像以前那么一般了。

【讨论】:

  • 我可以有多个默认值吗?因此,例如,这仅在操作名称为 Index 时有效。假设我有另一种方法,它有两个参数,分别是约会 ID 和参加者 ID,在这种情况下如何使这条路线工作?
  • 如果你的 url 是 /Response/AnotherMethod/ 它会走这条路线。
  • 但我将 url 设置为 url: "Response/{appointmentId}/{attendeeId}" 只是为了隐藏操作。现在在这种情况下,另一种方法不起作用。我可能不得不提到它才能使用另一种方法?
  • 请提供您希望拥有的网址
  • @Biplov13 MVC 路由从上到下选择第一个匹配的路由,即使它不是最佳选择。您希望按特定顺序放置路线。如果您的默认路由是列表中的第一个,它甚至不会检查其他路由。把你最具体的路线放在第一位,然后把更一般的路线放在最后。 “我可以有多个默认值吗” - 我希望这能回答你的问题。
猜你喜欢
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多