.NET MVC routing - catchall at start of route?
Asked Answered
S

1

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.

Sordello answered 26/3, 2014 at 14:59 Comment(0)
J
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.

Jericajericho answered 26/3, 2014 at 19:22 Comment(1)
Thanks! I didn't know you could do this. Works well!Sordello

© 2022 - 2024 — McMap. All rights reserved.