19

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).

0

1 Answer 1

35

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 }
);
Sign up to request clarification or add additional context in comments.

2 Comments

How can we achieve this with Attribute Routing?
In RouteConfig.cs before routes.MapRoute insert routes.MapMvcAttributeRoutes();. and than you can use attribute routing before action [Route("~/About")]. you need to prefix with a tilde to override the controller route. see stackoverflow.com/a/34712201/9258504

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.