ASP.NET MVC - Removing controller name from URL
To update this for 2016/17/18 - the best way to do this is to use Attribute Routing.
The problem with doing this in RouteConfig.cs is that the old route will also still work - so you'll have both
http://example.com/MyController/MyAction
AND
http://example.com/MyAction
Having multiple routes to the same page is bad for SEO - can cause path issues, and create zombie pages and errors throughout your app.
With attribute routing you avoid these problems and it's far easier to see what routes where. All you have to do is add this to RouteConfig.cs (probably at the top before other routes may match):
routes.MapMvcAttributeRoutes();
Then add the Route Attribute to each action with the route name, eg
[Route("MyAction")]
public ActionResult MyAction()
{
...
}
Here is the steps for remove controller name from HomeController
Step 1: Create the route constraint.
public class RootRouteConstraint<T> : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
return rootMethodNames.Contains(values["action"].ToString().ToLower());
}
}
Step 2:
Add a new route mapping above your default mapping that uses the route constraint that we just created. The generic parameter should be the controller class you plan to use as your “Root” controller.
routes.MapRoute(
"Root",
"{action}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { isMethodInHomeController = new RootRouteConstraint<HomeController>() }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Now you should be able to access your home controller methods like so: example.com/about, example.com/contact
This will only affects HomeController. All other Controllers will have the default routing functionality.
You should map new route in the global.asax (add it before the default one), for example:
routes.MapRoute("SpecificRoute", "{action}/{id}", new {controller = "MyController", action = "Index", id = UrlParameter.Optional});
// default route
routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} );