Search code examples
c#asp.net-mvcasp.net-routingmaproute

custom mapRoute for special controller and action to be like this in MVC: http://example.com/someValue


I have this default mapRoute:

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

and some other mapRoutes for some other sontrollers before default,

now, I want a mapRoute for special controller to show the url like : myDomain.com/someValue, but when I use this:

routes.MapRoute(
name: "categories",
url: "{sub}",
defaults: new { controller = "cat", action = "Index" }
);

all of my url.Actions which have "Index" as action like @Url.Action("index","login") not work, I have also used :

sub=UrlParameter.Optional

and

sub=""

, but they did not work, what should I do ?


Solution

  • Your categories route catches all urls because it is match with the role. You need to write a custom constraint class to filter out unmatched subs form your database for example.

    public class MyCatConstraint : IRouteConstraint
    {
        // suppose this is your cats list. In the real world a DB provider 
        private string[] _myCats = new[] { "cat1", "cat2", "cat3" };
    
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            // return true if you found a match on your cat's list otherwise false
            // in the real world you could query from DB to match cats instead of searching from the array.  
            if(values.ContainsKey(parameterName))
            {
                return _myCats.Any(c => c == values[parameterName].ToString());
            }
            return false;
        }
    }
    

    and then add this constraint to your route.

    routes.MapRoute(
        name: "categories",
        url: "{sub}",
        defaults: new { controller = "cat", action = "Index" }
        ,constraints: new { sub = new MyCatConstraint() }
        );