问题描述
有什么办法我可以匹配:
Is there any way I can match:
/a/myApp/Feature
/a/b/c/myApp/Feature
/x/y/z/myApp/Feature
$ 2 b $ b
与路由,不知道具体是对myApp /功能之前路径是什么
with a route that doesn't specifically know what the path before myApp/Feature 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.
如果我只是尝试{路径} /对myApp /功能,这将匹配/ A /对myApp /功能,而不是/ A / b / C /对myApp /功能。
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 = @".+" });
我这样做的原因是,我建立的是在一个CMS使用的功能,并且可以在网站结构的任何地方坐 - 我只能肯定对路径,而不是开始的结束
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.
推荐答案
您可以使用约束的是,
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 }
);
那么下面的网址,应该由被拦截功能
行动
/a/myApp/Feature
/a/b/c/myApp/Feature
/x/y/z/myApp/Feature
希望这有助于
这篇关于.NET MVC路由 - 包罗万象的路线开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!