2013-06-05 21 views
2

我在下面我的ASP.NET應用程序映射網址:ASP.NET圖路線與精確匹配約束

 context.MapRoute(
      "Product_v1_DataExchange", 
      "v1/xch", 
      new { controller = "Data", action = "Exchange" }); 

     context.MapRoute(
      "Product_v1_Register", 
      "v1/register", 
      new { controller = "Registration", action = "Register" }); 

我只想以下網址的工作:

http://servername/v1/xch 
http://servername/v1/register 

但以下網址也工作得很好:

http://servername/v1/xch?test 
http://servername/v1/register/?*e/ 
http://servername/v1//./register/./?* 

我怎樣才能把約束,使只有定義的靜態URL將被允許?

+0

你想實現與查詢字符串的URL是什麼?一個404錯誤,或者302重定向到querty-stringless url? (或匹配其他路線?) – jbl

+0

是的,如果網址不是靜態網址,應該是404。 –

回答

2

創建一個新的RouteConstraint這樣的:

public class ExactMatchConstraint : IRouteConstraint 
{ 
    private readonly bool _caseSensitive; 

    public ExactMatchConstraint(bool caseSensitive = false) 
    { 
     this._caseSensitive = caseSensitive; 
    } 

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     return 0 == String.Compare(route.Url.Trim('/'), httpContext.Request.RawUrl.Trim('/'), !this._caseSensitive); 
    } 
} 

然後使用它:

routes.MapRoute(
     "Custom", 
     "My/Custom", 
     new { controller = "Home", action = "Custom" }, 
     new { exact = new ExactMatchConstraint(/*true for case-sensitive */) } 
    ); 

結果:

/My/Custom (200 OK) 
/My/Custom/ (200 OK) 

/My/Custom/k (404 NOT FOUND) 
/My/Custom/k/v (404 NOT FOUND) 
/My/Custom/? (404 NOT FOUND) 
/My/Custom/?k=v (404 NOT FOUND)