我定义了一个派生自 ValidationAttribute 的新属性。例如
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ValidateDataAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
// some logic
return true;
}
}
我面临的问题是,对于给定的 Post/Put 请求,“IsValid”方法被调用了两次。如果 ModelState 无效,这将导致重复错误消息。知道可能出了什么问题吗?
示例用法:
public class Test
{
[Required]
[ValidateData]
public string Data {get;set;}
}
最佳答案
您已添加 [Required] 和 [ValidateData] 属性。
我想如果您删除 required 属性,这应该可以正常工作,因为它会做同样的事情。两者都继承自ValidateAttribute
公开课测试
{
[必需的]
公共(public)字符串数据 {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);
}
关于c# - Asp.net Web Api - 验证属性被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23822720/