Standard MVC 5 template.
So I'm trying to understand and create a named route to be used like:
<a href="@Url.RouteUrl(routeName: "myroute", routeValues: new { code = "123" })">this link</a>
In the Home Controller:
[Route("Home/DoIt", Name = "myroute"), HttpGet]
public ActionResult DoIt(string code)
{
return View();
}
MvcAttributeRouting is of course enabled in RoutConfig.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapMvcAttributeRoutes();
}
Because if it wasn't enabled, one will get:
A route named 'myroute' could not be found in the route collection. Parameter name: name
But I am getting:
The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Home/DoIt
What am I doing wrong?
EDIT: Obviously, I'm doing something wrong with the Route attribute, because even this doesn't work:
[Route("DoIt")]
or
[Route("Home/DoIt")]
Both give me 404, regardless of the request URL being http://localhost/Home/DoIt or http://localhost/DoIt
The order in which you place the MapMvcAttributeRoutes
line is important. You have it in the wrong location. It must be called before the default route.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Add this to get attribute routes to work
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Routing works like a switch case statement. The first match wins. But if you put the default route first, it will match every URL with 0, 1, 2, or 3 segments and effectively override any attribute routes of those lengths.