【问题标题】:.NET MVC routing - catchall at start of route?.NET MVC 路由 - 路由开始时的包罗万象?
【发布时间】:2014-05-05 02:05:20
【问题描述】:

有什么办法可以匹配:

/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 中使用的功能,并且可以位于站点结构中的任何位置 - 我只能确定路径的结束,而不是开始。

【问题讨论】:

    标签: c# asp.net-mvc-4 asp.net-mvc-routing


    【解决方案1】:

    您可以为此使用约束,

    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应该被Featureaction拦截

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

    希望这会有所帮助。

    【讨论】:

    • 谢谢!我不知道你能做到这一点。效果很好!
    猜你喜欢
    • 2016-08-20
    • 2011-10-13
    • 1970-01-01
    • 2011-04-02
    • 2021-04-25
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多