2014-11-08 36 views
1

我的路線:一個與ASP.net MVC路線多值路徑參數約束

routes.MapRoute(
     name: "Without Controller", 
     url: "{id}", 
     defaults: new { controller = "myControler", action = "Index", id = UrlParameter.Optional }, 
     constraints: new { id = new NotEqual("Home")}); 

定製路線:

public class NotEqual : IRouteConstraint 
    { 
     private readonly string _match = String.Empty; 

     public NotEqual(string match) 
     { 
      _match = match; 
     } 

     public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
     { 
      return String.Compare(values[parameterName].ToString(), _match, System.StringComparison.OrdinalIgnoreCase) != 0; 
     } 

    } 

問:我需要篩選既「首頁「和」登錄「ids.How can I do it?任何幫助將不勝感激。

constraints: new { id = new NotEqual("Home")});//I need to give "Login" also ? 
+0

爲什麼不通過一個CSV和內部處理它?即NotEquals(「Home,Login」)'。 – webnoob 2014-11-08 21:14:48

回答

1

正如我的意見建議,這樣的事情:

public class NotEqual : IRouteConstraint 
{ 
    private readonly List<string> _matches; 

    public NotEqual(string matches) 
    { 
     _matches = matches.Split(',').ToList(); 
    } 

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     return !_matches.Contains(values[parameterName].ToString()); 
    } 

} 

然後:

constraints: new { id = new NotEqual("Home,Login")}); 
+0

非常感謝Bro.It的工作:) – Sampath 2014-11-08 21:59:49

+1

很高興我能幫忙,感謝編輯:) – webnoob 2014-11-08 22:02:54

0

您可以使用PARAMS

public NotEqual(params string[] matches) 
{ 
    _match = match.Join(",", matches); 
} 
0
public class NotEqual : IRouteConstraint 
    { 
     string[] _matches; 

     public NotEqual(string[] matches) 
     { 
      _matches = matches; 
     } 

     public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
     { 
      return !_matches.Any(m => string.Equals(m, values[parameterName].ToString(), StringComparison.InvariantCultureIgnoreCase)); 
     } 
    } 

然後在您的路線配置:

constraints: new { id = new NotEqual(new string[] { "Home", "Login" })});