gpt4 book ai didi

c# - .NET MVC 路由 - 路由开始时的包罗万象?

转载 作者:太空狗 更新时间:2023-10-29 20:13:33 24 4
gpt4 key购买 nike

有什么方法可以匹配:

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

但是你不能在路线的起点放置一个 catchall。

如果我只是尝试“{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 中使用的功能,并且可以位于站点结构中的任何位置 - 我只能确定路径的终点,而不是起点。

最佳答案

你可以为此使用约束,

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

那么下面的url应该被Feature action拦截

/a/myApp/Feature

/a/b/c/myApp/Feature

/x/y/z/myApp/Feature

希望这对您有所帮助。

关于c# - .NET MVC 路由 - 路由开始时的包罗万象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22664924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com