如果第一次验证失败,如何防止执行下一个ValidationAttribute?
例如,如果(类别“ id” <= 0),则不要尝试检查它是否存在。 因为现在,当我执行“ PUT / api / categories / -1”时,我得到了:
{
"id": [
"id must be greater or equal to 0",
"Entity with such Id was not found!"
]
}
我要阻止进一步验证的方法:
[HttpPut("{id}")]
public ActionResult UpdateCategory([Min(0)][CategoryExists] int id, [FromBody] Category category)
{
return new OkResult();
//if (category.Id == 0) {
// return new BadRequestObjectResult("Id property is required!");
//}
//_context.Category.Update(category);
//_context.SaveChanges();
}
最小属性
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public class MinAttribute : ValidationAttribute
{
private int _minVal;
public MinAttribute(int minVal)
{
_minVal = minVal;
}
public override bool IsValid(object value)
{
if ((int)value >= _minVal)
{
return true;
}
else
{
return false;
}
}
public override string FormatErrorMessage(string name)
{
return $"{name} must be greater or equal to {_minVal}";
}
}
CategoryExists属性
public class CategoryExistsAttribute : ValidationAttribute
{
public CategoryExistsAttribute()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var context = (TechDbContext)validationContext.GetService(typeof(TechDbContext));
var result = from i in context.Category
where i.Id == (int)value
select i;
Category category = result.SingleOrDefault();
if (category == null)
{
return new ValidationResult("Entity with such Id was not found!");
}
return ValidationResult.Success;
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(name);
}
}
答案 0 :(得分:0)
为Category
对象编写扩展方法,以验证您的所有需求。
例如
internal static bool Validate(this Category category){
if (category.Id <= 0) {
return false;
}
// Add more validations or throw exceptions if needed.
return true;
}
因此,您可以从控制器中执行此操作。
if(category.Validate()){
//proceed to other business logic
}
有关数据验证的更多详细信息,请阅读this