我有什么方法可以匹配:
/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中使用的功能,并且可以位于站点结构中的任何位置 - 我只能确定路径的结束,而不是开头。< / p>
答案 0 :(得分:8)
您可以使用约束
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
动作
/a/myApp/Feature
/a/b/c/myApp/Feature
/x/y/z/myApp/Feature
希望这会有所帮助。