Routing with and without controller name in ASP.NET MVC 4

↘锁芯ラ 提交于 2019-11-27 02:11:57

问题


I'm using ASP.NET MVC 4 and I have some problems settings up my routes. Could you tell my how to set up my routes to point urls to actions as follows:

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

It's the url "/About" that messes things up for me, i.e. a url that does not specify the controller. If I make that one work the others that do specify controller stop working. I could just create a separate controller for "/About" I guess, but I'd rather not if I don't have to (I have more urls following that pattern).


回答1:


This should do it:

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 }
);


来源:https://stackoverflow.com/questions/15836401/routing-with-and-without-controller-name-in-asp-net-mvc-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!