Asp.net Web Api -验证属性被调用两次
本文关键字:调用 两次 属性 Web net Api 验证 Asp | 更新日期: 2023-09-27 18:04:39
我定义了一个从ValidationAttribute派生的新属性。例如
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ValidateDataAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
// some logic
return true;
}
}
我面临的问题是"IsValid"方法被调用两次,对于给定的Post/Put请求。在无效ModelState的情况下,这会导致错误消息的重复。你知道会出什么问题吗?
示例用法:public class Test
{
[Required]
[ValidateData]
public string Data {get;set;}
}
您已经添加了[Required]和[ValidateData]属性。
我想这应该工作得很好,如果你删除所需的属性,因为它做同样的事情。两者都继承自ValidateAttribute
public class Test
{
[Required]
public string Data {get;set;}
}
请查看所需的属性类
// 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);
}