.NET MVC routing - catchall at start of route?

前端 未结 1 1335
悲哀的现实
悲哀的现实 2021-01-05 05:43

Is there any way I can match:

/a/myApp/Feature

/a/b/c/myApp/Feature

/x/y/z/myApp/Feature

with a route that doesn\'t specifically know wha

相关标签:
1条回答
  • 2021-01-05 06:28

    You can use a constraint for that,

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

    then the following urls should be intercepted by Feature action

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

    hope this helps.

    0 讨论(0)
提交回复
热议问题