ASP.NET WEB API 2-每个请求两次触发ModelBinding [英] ASP.NET WEB API 2 - ModelBinding Firing twice per request

查看:100
本文介绍了ASP.NET WEB API 2-每个请求两次触发ModelBinding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的验证属性,当我通过POST向服务器发出请求时,会在该属性上触发IsValid方法两次.

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.

我已经使用Fiddler检查了该请求仅被触发一次,因此情况是1个请求具有两次模型绑定触发.

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

推荐答案

Ninject存在问题,它使ModelValidatorProviders的数量增加了一倍.

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

这篇关于ASP.NET WEB API 2-每个请求两次触发ModelBinding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆