在ASP.net MVC路由约束上具有多个值的一个路由参数

时间:2014-11-08 20:04:16

标签: asp.net-mvc routes

我的路线:

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

    }

问题我需要过滤“主页”和“登录”ID。我该怎么做?任何帮助都将受到高度赞赏。

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

3 个答案:

答案 0 :(得分: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")});

答案 1 :(得分:0)

你可以使用params

public NotEqual(params string[] matches)
{
    _match = match.Join(",", matches);
}

答案 2 :(得分: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" })});