简体   繁体   中英

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

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

The problem was indeed caused by Ninject. There are two model validator providers that register the validation attributes ModelValidatorProvider and NinjectDefaultModelValidatorProvider . In my case I only unbinded the ModelValidatorProvider in the Ninject configuration file, under the creation of a new Kernel:

var kernel = new StandardKernel();
kernel.Unbind<ModelValidatorProvider>();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM