abp vnext验证 电脑版发表于:2022/7/11 9:25 ### 验证DTO 微软官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/validation?view=aspnetcore-7.0 **数据注解 Attribute** 使用数据注解是一种以声明式对DTO进行验证的简单方法. 示例 : ``` public class CreateBookDto { [Required] [StringLength(100)] public string Name { get; set; } [Required] [StringLength(1000)] public string Description { get; set; } [Range(0, 999.99)] public decimal Price { get; set; } } ``` 当使用该类作为应用服务或控制器的参数时,将对其自动验证并抛出本地化异常(由ABP框架处理). **IValidatableObject** IValidatableObject can be implemented by a DTO to perform custom validation logic. CreateBookDto in the following example implements this interface and checks if the Name is equals to the Description and returns a validation error in this case. 可以将DTO实现 IValidatableObject 接口进行自定义验证逻辑. 下面的示例中 CreateBookDto 实现了这个接口,并检查 Name 是否等于 Description 并返回一个验证错误. ``` using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Acme.BookStore { public class CreateBookDto : IValidatableObject { [Required] [StringLength(100)] public string Name { get; set; } [Required] [StringLength(1000)] public string Description { get; set; } [Range(0, 999.99)] public decimal Price { get; set; } public IEnumerable<ValidationResult> Validate( ValidationContext validationContext) { if (Name == Description) { yield return new ValidationResult( "Name and Description can not be the same!", new[] { "Name", "Description" } ); } } } } ``` 原文:https://docs.abp.io/zh-Hans/abp/latest/Validation