Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET MVC routing - catchall at start of route?

Is there any way I can match:

/a/myApp/Feature

/a/b/c/myApp/Feature

/x/y/z/myApp/Feature

with a route that doesn't specifically know what the path before myApp/Feature is?

What I essentially want to do is:

RouteTable.Routes.MapRoute(
  "myAppFeatureRoute", "{*path}/myApp/Feature",
  new { controller = "myApp", action = "Feature" });

but you can't put a catchall at the start of a route.

If I just try "{path}/myApp/Feature", that will match "/a/myApp/Feature" but not "/a/b/c/myApp/Feature".

I tried a regex catchall as well, that did nothing to help.

RouteTable.Routes.MapRoute(
  "myAppFeatureRoute", "{path}/myApp/Feature",
  new { controller = "myApp", action = "Feature", path = @".+" });

The reason I'm doing this is that I am building a feature that is used in a CMS, and can sit anywhere in the site structure - I can only be certain about the end of the path, not the beginning.

like image 233
tenshi_a Avatar asked Mar 26 '14 14:03

tenshi_a


1 Answers

You can use a constraint for that,

public class AppFeatureUrlConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (values[parameterName] != null)
        {
            var url = values[parameterName].ToString();
            return url.Length == 13 && url.EndsWith("myApp/Feature", StringComparison.InvariantCultureIgnoreCase) ||
                    url.Length > 13 && url.EndsWith("/myApp/Feature", StringComparison.InvariantCultureIgnoreCase);
        }
        return false;
    }
}

using it as,

routes.MapRoute(
    name: "myAppFeatureRoute",
    url: "{*url}",
    defaults: new { controller = "myApp", action = "Feature" },
    constraints: new { url = new AppFeatureUrlConstraint() }
    );

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

then the following urls should be intercepted by Feature action

/a/myApp/Feature

/a/b/c/myApp/Feature

/x/y/z/myApp/Feature

hope this helps.

like image 74
shakib Avatar answered Nov 08 '22 01:11

shakib