You have 2 issues:
- Your RegEx does not contain anchors (
^
and $
) to delimit the string you are attempting to match. So, it is matching any string that contains any of these letters.
- Your URL will always match the default route, so even if your custom route doesn't match, you will still get to the page. The default route will match any URL that is 0, 1, 2, or 3 segments in length.
You can get around this by removing your custom route and using an IgnoreRoute
(which behind the scenes uses a StopRoutingHandler
) to prevent those specific URLs from matching.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("Homepage/Index/{soortAanbod}",
new { soortAanbod = new NegativeRegexRouteConstraint(@"^a$|^b$|^c$|^d$|^e$") });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
There is a caveat, though. RegEx's are not very good at doing negative matches, so if you are not a RegEx guru the simplest solution is to build a NegativeRegexRouteConstraint
to handle this scenario.
public class NegativeRegexRouteConstraint : IRouteConstraint
{
private readonly string _pattern;
private readonly Regex _regex;
public NegativeRegexRouteConstraint(string pattern)
{
_pattern = pattern;
_regex = new Regex(pattern, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (parameterName == null)
throw new ArgumentNullException("parameterName");
if (values == null)
throw new ArgumentNullException("values");
object value;
if (values.TryGetValue(parameterName, out value) && value != null)
{
string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
return !_regex.IsMatch(valueString);
}
return true;
}
}