简体   繁体   中英

Asp.net Web Api - Validation Attribute getting invoked twice

I have defined a new attribute derived from 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. 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.

I guess this should work fine if you remove required attribute, as it does the same thing. Both are inherited from 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);
}

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