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

haa*_*gel 14 asp.net-mvc asp.net-mvc-routing asp.net-mvc-4

我正在使用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)

这是网址"/关于"让我感到烦恼,即一个没有指定控制器的网址.如果我使那个工作指定控制器的其他人停止工作.我可以为"/ About"创建一个单独的控制器,我想,但是如果我不需要,我宁愿不这样做(我有更多的网址遵循该模式).

Dar*_*rov 32

这应该这样做:

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 }
);
Run Code Online (Sandbox Code Playgroud)