1

My Route :

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

Custom Route :

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

    }

Question : I need to filter both "Home" and "Login" ids.How can I do it ? Any help would be highly appreciated.

constraints: new { id = new NotEqual("Home")});//I need to give "Login" also ?
1
  • Why not pass a CSV through and process it inside? i.e NotEquals("Home,Login"). Commented Nov 8, 2014 at 21:14

2 Answers 2

1

As suggested in my comments, something like this:

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

}

Then:

constraints: new { id = new NotEqual("Home,Login")});
Sign up to request clarification or add additional context in comments.

Comments

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

Then in your route config:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.