在ASP.NET MVC 4中,使用控制器名称进行路由和不使用控制器名称进行路由的方法

19

我正在使用ASP.NET MVC 4,遇到了一些路由设置的问题。您能告诉我如何设置路由以便将URL指向以下操作:

  • "/"(或 "/Start")=> PublicController.Start()
  • "/About" => PublicController.About()
  • "/MyPage"(或 "/MyPage/Summary")=> MyPageController.Summary()
  • "/MyPage/Invoices" => MyPageController.Invoices()
  • "/MyPage/Invoice/72" => MyPageController.Invoice(int id)

对我来说,URL "/About" 搞砸了,即一个不指定控制器的URL。如果让它起作用,则指定控制器的其他路由将停止工作。我猜可以为 "/About" 创建一个单独的控制器,但如果没有必要的话,我宁愿不这样做(我有更多遵循该模式的URL)。

1个回答

35
这样应该可以:

这样做应该就可以了:

routes.MapRoute(
    name: "About",
    url: "About",
    defaults: new { controller = "Public", action = "About" }
);

routes.MapRoute(
    name: "MyPageSummary",
    url: "MyPage",
    defaults: new { controller = "MyPage", action = "Summary" }
);

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

我们如何使用属性路由来实现这一点? - Hammad Sajid
在 RouteConfig.cs 文件中,在 routes.MapRoute 之前插入 routes.MapMvcAttributeRoutes();。然后你就可以在动作方法上使用属性路由 [Route("~/About")]。需要注意的是,为了覆盖控制器路由,你需要在路由模板前加上波浪线。详情请参考 https://dev59.com/NlsW5IYBdhLWcg3wqo0x#34712201。 - SamBerk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接