Validating data in the service layer against DTOs, Entity Models, or something else?

核能气质少年 提交于 2019-12-06 09:24:41

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

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!");
   }
   ...
}

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).

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!