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

时间:2022-06-26 17:12:44

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:

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

  • "/" (or "/Start") => PublicController.Start()
  • “/”(或“/ Start”)=> PublicController.Start()
  • "/About" => PublicController.About()
  • “/ About”=> PublicController.About()
  • "/MyPage" (or "/MyPage/Summary") => MyPageController.Summary()
  • “/ MyPage”(或“/ MyPage / Summary”)=> MyPageController.Summary()
  • "/MyPage/Invoices" => MyPageController.Invoices()
  • “/ MyPage / Invoices”=> MyPageController.Invoices()
  • "/MyPage/Invoice/72" => MyPageController.Invoice(int id)
  • “/ 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).

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

1 个解决方案

#1


28  

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

#1


28  

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