2014-11-08 38 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" })});