0
votes

.NET MVC. I am having some problems defining and using custom routes. I have a controller with just 2 actions. These action methods receive 2 parameters each. I have added a custom route in RouteConfig.cs (before the default route), like this

  routes.MapRoute(
     name: "customRoute",
     url: "MyController/{action}/{entityType}/{id}",
     defaults: new { controller = "MyController", action = "Index", entityType = UrlParameter.Optional, id = UrlParameter.Optional }
  );

this works if MyController does contain an Index method (and corresponding view). the problem is, MyController does not contain an Index method (only the 2 action methods refered before), and I want the route.default to be something like Home/Index instead. but if I change the route to this:

  routes.MapRoute(
     name: "customRoute",
     url: "MyController/{action}/{entityType}/{id}",
     defaults: new { controller = "Home", action = "Index", entityType = UrlParameter.Optional, id = UrlParameter.Optional }
  );

it does not work. Apparently, the controller in route.url must be the same as the one in route.defaults...

CORRECTION: the route works for a correct url, but for an incorrect one (for example adding another parameter at the end) it shows 404 error (makes sense, because MyController.Index does not exists)

so, how can this be achieved?

1
Can you give us example of your controller method signature and the url you are trying to use?the_lotus

1 Answers

0
votes

url: "MyController/{action}/{entityType}/{id}"

Here, what you are saying is the URL pattern for your custom route should start with MyController(My/). If the url pattern does not match with the configured routes(including the default one) you will have 404 Error.

I can suggest 2 ways of achieving what you want...

Either create a third method in your MyController that will act as the default one and its task would be to redirect to Home/Index.

Or

Create a new method in Home controller having parameters for entityType and Id.

You can't create an overload for Home/Index because you can only have a maximum of 2 action methods with the same name on a controller.

See this.

Routing: The current request for action [...] is ambiguous between the following action methods