.NET MVC路由 – 在路由开始时捕获?

有什么方法可以匹配:

/a/myApp/Feature /a/b/c/myApp/Feature /x/y/z/myApp/Feature 

有一条路线不明确知道myApp / Feature之前的路径是什么?

我基本上想做的是:

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

但是你不能在路线的开头放一个笼子。

如果我只是尝试“{path} / myApp / Feature”,那将匹配“/ a / myApp / Feature”而不是“/ a / b / c / myApp / Feature”。

我也尝试了一个正则表达式的捕获,没有任何帮助。

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

我这样做的原因是我正在构建一个在CMS中使用的function,并且可以位于站点结构中的任何位置 – 我只能确定路径的结束,而不是开头。

你可以使用约束,

 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; } } 

用它作为,

 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 } ); 

然后应通过Feature操作拦截以下url

 /a/myApp/Feature /a/b/c/myApp/Feature /x/y/z/myApp/Feature 

希望这可以帮助。