HttpRouteConstraint is called multiple times if the Match method returns false

Topics: ASP.NET Web API
Sep 3, 2012 at 10:04 AM

If the Match method of an IHttpRouteConstraint implementation returns false, the route constraint is called twice. Repro:


public class OptionalRegExConstraint : IHttpRouteConstraint {

    private readonly string _regEx;

    public OptionalRegExConstraint(string expression) {

        if (string.IsNullOrEmpty(expression)) {

            throw new ArgumentNullException("expression");

        _regEx = expression;

    public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection) {

        Console.WriteLine("OptionalRegExConstraint.Match is running");

        if (values[parameterName] != RouteParameter.Optional) {

            object value;
            values.TryGetValue(parameterName, out value);
            string input = Convert.ToString(value, CultureInfo.InvariantCulture);

            string pattern = "^(" + _regEx + ")$";
            return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

        return true;

Route registration:

protected void Application_Start(object sender, EventArgs e) {

    var routes = GlobalConfiguration.Configuration.Routes;

        new { id = RouteParameter.Optional },
        new { id = new OptionalRegExConstraint(@"\d+") }



I looked at the call stack but couldn't figure out why this is called twice. Is this a bug or an expected behavior?

Sep 9, 2012 at 12:09 PM

Hey guys,

do u have any clue on this issue?

Sep 10, 2012 at 7:37 PM

We will have to investigate. Could you please file an issues on this in the issue tracker with the instructions on how to reproduce the issue?

Thanks for bringing this issue to our attention.

Sep 10, 2012 at 11:17 PM


thanks for getting back Dan. I filed an issue: