Search code examples
c#asp.netasp.net-web-api2model-validationvalidationattribute

ASP.NET WEB API 2 - ModelBinding Firing twice per request


I have a custom validation attribute, that when I make a request to the server via a POST, is firing the IsValid method on the attribute twice.

Its resulting in the error message returned to be duplicated.

I've checked using Fiddler that the request is only ever fired once, so the situation is 1 request with model binding firing twice.

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MinimumAgeAttribute : ValidationAttribute
{
    private readonly int _minimumAge;

    public MinimumAgeAttribute(int minimumAge)
    {
        _minimumAge = minimumAge;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        DateTime date;

        if (DateTime.TryParse(value.ToString(), out date))
        {
            if (date.AddYears(_minimumAge) < DateTime.Now)
            {
                return ValidationResult.Success;
            }
        }

        return new ValidationResult("Invalid Age, Clients must be 18 years or over");
    }
}

Solution

  • The problem was with Ninject, it was doubling up the number of ModelValidatorProviders.

    I've added this binding to prevent the problem.

    container.Rebind<ModelValidatorProvider>().To<NinjectDefaultModelValidatorProvider>();