1.Data Annotations
public class studentdto
{
[Display(Name ="ID")]
public int sid { get; set; }
[Display(Name = "性别")]
public int xingbie { get; set; }
[Display(Name = "班级ID")]
public int cid { get; set; }
[Display(Name = "个人简介")]
[Required(ErrorMessage = "{0}不能为空")]
[MaxLength(5, ErrorMessage = "{0}字符串不能大于{1}")]
//[StringLength(5,MinimumLength =1,ErrorMessage = "{0}字符串大于{2}小于{1}")]
public string info { get; set; }
}
验证失败:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|a78a6735-45603cc657ae4574.",
"errors": {
"info": [
"个人简介字符串不能大于5"
]
}
}
2.IValidatableObject
public class studentdto:IValidatableObject
{
[Display(Name ="ID")]
public int sid { get; set; }
[Display(Name = "性别")]
public int xingbie { get; set; }
[Display(Name = "班级ID")]
public int cid { get; set; }
[Display(Name = "个人简介")]
[Required(ErrorMessage = "{0}不能为空")]
[MaxLength(5, ErrorMessage = "{0}字符串不能大于{1}")]
//[StringLength(5,MinimumLength =1,ErrorMessage = "{0}字符串大于{2}小于{1}")]
public string info { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
//假设班级id不能等于学生id(瞎比假设,为了示例)
if (cid==sid)
{
yield return new ValidationResult(errorMessage: "班级id不能等于学生id", new[] { nameof(sid), nameof(cid) });
}
}
}
验证失败
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|a1c054b2-4e59b0daf2a0d8c5.",
"errors": {
"cid": [
"班级id不能等于学生id"
],
"sid": [
"班级id不能等于学生id"
]
}
}
**注意:**Data Annotations优先于IValidatableObject 验证,当Data Annotations验证失败,将不进入IValidatableObject 验证。
3.自定义Attribute
public class StudentsidAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var addDto = (studentdto)validationContext.ObjectInstance;
if (addDto.cid.ToString() == addDto.info)
{
return new ValidationResult(errorMessage: "验证失败", new[] { nameof(addDto.cid), nameof(addDto.info) });
}
return ValidationResult.Success;
}
}
使用
[StudentsidAttribute]//添加在这里
public class studentdto:IValidatableObject
{
[Display(Name ="ID")]
public int sid { get; set; }
[Display(Name = "性别")]
public int xingbie { get; set; }
[Display(Name = "班级ID")]
public int cid { get; set; }
[Display(Name = "个人简介")]
[Required(ErrorMessage = "{0}不能为空")]
[MaxLength(5, ErrorMessage = "{0}字符串不能大于{1}")]
//[StringLength(5,MinimumLength =1,ErrorMessage = "{0}字符串大于{2}小于{1}")]
public string info { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
//假设班级id不能等于学生id(瞎比假设,为了示例)
if (cid==sid)
{
yield return new ValidationResult(errorMessage: "班级id不能等于学生id", new[] { nameof(sid), nameof(cid) });
}
}
}
注意 自定义Attribute 可以作用在类上 所以优先级 大于Data Annotations大于IValidatableObject 验证