简体   繁体   English

Asp.net Web Api - 验证属性被调用两次

[英]Asp.net Web Api - Validation Attribute getting invoked twice

I have defined a new attribute derived from ValidationAttribute. 我已经定义了一个从ValidationAttribute派生的新属性。 Eg 例如

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class ValidateDataAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            // some logic
            return true;
        }
    }

The problem I am facing is that the "IsValid" method is getting invoked twice, for a given Post/Put request. 我面临的问题是,对于给定的Post / Put请求,“IsValid”方法被调用两次。 This is causing repetition of error message, in case of invalid ModelState. 如果模型状态无效,则会导致重复出现错误消息。 Any idea what could possibly be going wrong? 知道什么可能出错吗?

Sample usage: 样品用法:

public class Test
    {
        [Required]
        [ValidateData]
        public string Data {get;set;}
    }

You have added [Required] and [ValidateData] attribute. 您已添加[必需]和[ValidateData]属性。

I guess this should work fine if you remove required attribute, as it does the same thing. 我想这应该可以正常工作,如果您删除所需的属性,因为它做同样的事情。 Both are inherited from ValidateAttribute 两者都继承自ValidateAttribute

public class Test { [Required] public string Data {get;set;} }

Please have a look at the required attribute class as well 请查看所需的属性类

   // Summary:
//     Specifies that a data field value is required.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class RequiredAttribute : ValidationAttribute
{
    // Summary:
    //     Initializes a new instance of the System.ComponentModel.DataAnnotations.RequiredAttribute
    //     class.
    public RequiredAttribute();

    // Summary:
    //     Gets or sets a value that indicates whether an empty string is allowed.
    //
    // Returns:
    //     true if an empty string is allowed; otherwise, false. The default value is
    //     false.
    public bool AllowEmptyStrings { get; set; }

    // Summary:
    //     Checks that the value of the required data field is not empty.
    //
    // Parameters:
    //   value:
    //     The data field value to validate.
    //
    // Returns:
    //     true if validation is successful; otherwise, false.
    //
    // Exceptions:
    //   System.ComponentModel.DataAnnotations.ValidationException:
    //     The data field value was null.
    public override bool IsValid(object value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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