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

落花浮王杯 提交于 2019-12-22 18:45:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!