2014-03-26 113 views
6

有什麼辦法我可以匹配:.NET MVC路由 - catchall在路由啓動?

/a/myApp/Feature 

/a/b/c/myApp/Feature 

/x/y/z/myApp/Feature 

與不知道具體是對myApp /功能之前的路徑是什麼路線?

我基本上想要做的是:

RouteTable.Routes.MapRoute(
    "myAppFeatureRoute", "{*path}/myApp/Feature", 
    new { controller = "myApp", action = "Feature" }); 

,但你不能把一個包羅萬象的在路線的起點。

如果我只是嘗試 「{}路徑/對myApp /功能」,這將匹配 「/ A /對myApp /功能」,而不是 「/ A/B/C /對myApp /功能」。

我嘗試了正則表達式包羅萬象的好,那什麼也沒做,以幫助。

RouteTable.Routes.MapRoute(
    "myAppFeatureRoute", "{path}/myApp/Feature", 
    new { controller = "myApp", action = "Feature", path = @".+" }); 

的原因,我這樣做是我建立了在一個CMS使用的功能,並且可以在網站結構的任何地方坐 - 我只能是某些關於路徑的終點,不開始。

回答

7

您可以使用一個約束,

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

那麼下面的網址應該Feature行動

/a/myApp/Feature 

/a/b/c/myApp/Feature 

/x/y/z/myApp/Feature 

希望被截獲這有助於。

+0

謝謝!我不知道你可以做到這一點。效果很好! –

+0

不客氣。 – shakib