根据DTO,实体模型或其他方式validation服务层中的数据?

我正在开发一个ASP.NET MVC项目。 在项目中,我有一个服务层,接受DTO进行CRUD操作。 当我需要validation业务逻辑时,validation器是否应该完全接受DTO,实体模型或其他内容?

例如:

public class ProductService: IProductService { public ValidationResult CreateProduct(ProductDTO productDto) { //call productValidator.Validate(productDto) on the DTO here? Product productEntityModel = mapper.Map(productDto); //or, call productValidator.Validate(productEntityModel) on the Entity model here? if(validationResult.Valid) { _dbContext.Products.Add(productEntityModel); _dbContext.SaveChanges(); } return validationResult } } 

一些想法:

  • 我在网上看过一些关于创建一个POCO的讨论,它可以有validation逻辑(而不是使用validation服务),甚至还有其他业务逻辑。 这是有道理的,但它还是一个必须进行管理和维护的产品的“代表”。
  • 对DTO进行validation似乎更合理,因为调用者正在向服务发送?

谢谢您的帮助!!

当我需要validation业务逻辑时,validation器是否应该完全接受DTO,实体模型或其他内容?

通常,我们使用DataAnnotationsViewModel类中执行validation,以便我们可以返回用户友好的ModelError 。 例如,

 public class LoginViewModel { [Display(Name = "Username")] [Required(ErrorMessage = "Please enter your username.")] public string UserName { get; set; } } public async Task Login(LoginModel model, string returnUrl) { if (ModelState.IsValid) { ... ModelState.AddModelError("", "User is not authorized!"); } ... } 

虽然您可以在ProductServicevalidation某些业务逻辑,但您无法返回MVC ModelError ,因为Service / Repository Layer不应该依赖于ASP.NET MVC(或任何UI组件)。

Service / Repository Layer中的大多数错误都是意外错误而不是用户错误。 我们在NLog或Log4Net中记录这些错误,并将用户重定向到自定义错误页面。