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 ?
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")});
You can use params
public NotEqual(params string[] matches)
{
_match = match.Join(",", matches);
}
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" })});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.