9

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.

1 Answer 1

10

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.

1
  • Thanks! I didn't know you could do this. Works well!
    – tenshi_a
    Mar 27, 2014 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.