How to remove the controller name from the URL in MVC 5. I tried to add the route in the route.config
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Special",
url: "action/{id}",
defaults: new { controller = "Home", action = "LandingIndex", id = UrlParameter.Optional }
);
}
}
When I tried to a access the URL by http://localhost:24220/LandingIndex it will prompt 404 error. how to resolve this issue
You could try inverting the routes definition by placing the more specialized route first. Also you probably didn't want to hardcode the action name as action
but rather use the {action}
placeholder:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Special",
url: "{action}",
defaults: new { controller = "Home", action = "LandingIndex" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Now when you navigate to /LandingIndex
, the LanginIndex
action on the Home
controller should be invoked.
Also notice that I have removed the optional {id}
placeholder from the first route. The reason for that is because if it were present, the routing engine would never use the second route. For example if you try to load /Home/Index
it will look for a Home
action on the Home
controller and passing it Index
as id
. If you want to have this {id}
token you will need to use a constraint to diambiguate with your second more general route definition. For example if your identifiers are always integers or follow some pattern, you could write a regex constraint that will match them.