ten*_*i_a 7 c# asp.net-mvc-routing asp.net-mvc-4
有什么方法可以匹配:
/a/myApp/Feature
/a/b/c/myApp/Feature
/x/y/z/myApp/Feature
Run Code Online (Sandbox Code Playgroud)
有一条路线不明确知道myApp/Feature之前的路径是什么?
我基本上想做的是:
RouteTable.Routes.MapRoute(
"myAppFeatureRoute", "{*path}/myApp/Feature",
new { controller = "myApp", action = "Feature" });
Run Code Online (Sandbox Code Playgroud)
但是你不能在路线的开头放一个笼子.
如果我只是尝试"{path}/myApp/Feature",那将匹配"/ a/myApp/Feature"而不是"/ a/b/c/myApp/Feature".
我也尝试了一个正则表达式,但没有任何帮助.
RouteTable.Routes.MapRoute(
"myAppFeatureRoute", "{path}/myApp/Feature",
new { controller = "myApp", action = "Feature", path = @".+" });
Run Code Online (Sandbox Code Playgroud)
我这样做的原因是我正在构建一个在CMS中使用的功能,并且可以位于站点结构中的任何位置 - 我只能确定路径的结束,而不是开头.
您可以使用约束,
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;
}
}
Run Code Online (Sandbox Code Playgroud)
用它作为,
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 }
);
Run Code Online (Sandbox Code Playgroud)
然后应该通过Feature行动拦截以下网址
/a/myApp/Feature
/a/b/c/myApp/Feature
/x/y/z/myApp/Feature
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.