问题
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");
}
}
回答1:
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>();
回答2:
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>();
来源:https://stackoverflow.com/questions/35889820/asp-net-web-api-2-modelbinding-firing-twice-per-request