1

How can I replicate this default MVC route code below but to work with multiple ActionResults that are in the home controller. I want them to work just like Index where you do not need /Home/Index in the url to hit example.com/index

 routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            
            );

I would like to hit example.com/about and example.com/contact without needing the the controller name in the beginning.

I have tried adding that same code but replaced Index with another action method and it works but it doesn't allow you to have more than 1 existing in this structure at the same time. Solution?

CodeQuest
  • 121
  • 1
  • 14

1 Answers1

1

Ok so I think I got it to work after reading this thread: ASP.NET MVC - Removing controller name from URL

In the RouteConfig I added the following right before the default route:

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 }
);

Then inside of the Controller whos name you are trying to remove from the URL you need to add this:

    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());
    }
}

Now if I go to example.com/about , it works and I don't have to use example.com/Home/About

Toto
  • 89,455
  • 62
  • 89
  • 125
CodeQuest
  • 121
  • 1
  • 14