Question

For www.demo.com/city/hotel-in-city

routes.MapRoute(
    name: "Search",
    url: "{city}/{slug}",
    defaults: new { controller = "Demo", action = "Index", city = UrlParameter.Optional}
);

For default

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

But when I call the index method of home controller www.demo.com/home/index it points to 1st route(index method of default controller).

How to handle default route ?

No correct solution

OTHER TIPS

The problem is that your "Search" route captures basically everything. One way of handling this is to create more-specific routes for the home controller, and put those first:

routes.MapRoute(
    name: "Home1",
    url: "/",
    defaults: new { action = "Index", controller = "Home" }
);

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

routes.MapRoute(
    name: "Search",
    url: "{city}/{slug}",
    defaults: new { controller = "Demo", action = "Index" }
);

This will filter out any URL with "Home" as the first parameter, and allow everything else through to the search.


If you have a lot of controllers, the above approach may be inconvenient. In that case, you could consider using a custom constraint to filter out either the default route, or the "Search" route, whichever one you decide to put first in the route config.

For example, the following constraint declares the match invalid, in case the routing engine has attempted to assign "Home" to the "city" parameter. You can modify this as needed, to check against all your controllers, or alternately, against a cached list of available city names:

public class SearchRouteConstraint : IRouteConstraint
{
    private const string ControllerName = "Home";

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return String.Compare(values["city"].ToString(), ControllerName, true) != 0;
    }
}

This will allow URLs starting with "/Home" through to the default route:

routes.MapRoute(
    name: "Search",
    url: "{city}/{slug}",
    defaults: new { controller = "Demo", action = "Index" },
    constraints: new { city = new SearchRouteConstraint() }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional, action = "Index", controller = "Home" }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top