根据DTO,实体模型或其他方法验证服务层中的数据? [英] Validating data in the service layer against DTOs, Entity Models, or something else?

查看:109
本文介绍了根据DTO,实体模型或其他方法验证服务层中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究ASP.NET MVC项目.在项目中,我有一个服务层,可以接受DTO进行CRUD操作.当我需要验证业务逻辑时,验证器应该接受DTO,实体模型还是其他全部东西?

I'm working on an ASP.NET MVC project. In the project I have a service layer that accepts DTOs for CRUD operations. When I need to validate business logic, should the validator accept DTOs, Entity Models, or something else entirely?

例如:

public class ProductService: IProductService
{
    public ValidationResult CreateProduct(ProductDTO productDto)
    {
       //call productValidator.Validate(productDto) on the DTO here?

        Product productEntityModel = mapper.Map<Product>(productDto);

        //or, call productValidator.Validate(productEntityModel) on the Entity model here?

        if(validationResult.Valid)
        {
            _dbContext.Products.Add(productEntityModel);
            _dbContext.SaveChanges();
        }

        return validationResult
    }
}

一些想法:

  • 我在网上看到过一些关于创建POCO的讨论,该POCO可以包含验证逻辑(而不是使用验证服务),甚至还可以包含其他业务逻辑.这是有道理的,但这是必须管理和维护的产品的又一个代表".
  • 验证DTO似乎更合理一点,因为那是呼叫者正在发送到服务?

感谢您的帮助!

推荐答案

当我需要验证业务逻辑时,验证者是否应该接受 DTO,实体模型还是其他所有东西?

When I need to validate business logic, should the validator accept DTOs, Entity Models, or something else entirely?

通常,我们使用DataAnnotationsViewModel类中执行验证,以便我们返回用户友好的ModelError.例如,

Normally, we perform validation in ViewModel class using DataAnnotations, so that we can return user friendly ModelError. For example,

public class LoginViewModel
{
   [Display(Name = "Username")]
   [Required(ErrorMessage = "Please enter your username.")]
   public string UserName { get; set; }
}

public async Task<ActionResult> Login(LoginModel model, string returnUrl)
{
   if (ModelState.IsValid)
   {
      ...
      ModelState.AddModelError("", "User is not authorized!");
   }
   ...
}

尽管您可以验证ProductService中的某些业务逻辑,但是您不能返回MVC ModelError,因为服务/存储层不应依赖于ASP.NET MVC(或任何UI组件).

Although you can validate some business logic inside ProductService, you cannot return MVC ModelError, since Service/Repository Layer should not depends on ASP.NET MVC (or any UI components).

服务/存储库层内部的大多数错误是意外错误,而不是用户错误.我们将这些错误记录在NLog或Log4Net中,然后将用户重定向到自定义错误页面.

Most of the error inside Service/Repository Layer are unexpected error instead of user error. We norammly log those error in NLog or Log4Net, and redirect user to custom error page.

这篇关于根据DTO,实体模型或其他方法验证服务层中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆