【发布时间】:2016-11-10 09:20:06
【问题描述】:
我有一个带有控制器和服务的 API,当调用控制器中的一个操作时,我必须应用验证,此验证需要检查数据库中的数据以验证其是否正确。
据我所知有两种处理方式
1-在调用“更新”之前验证以防止错误
public IActionResult UpdateCustomer(CustomerDto customer)
{
if (!customerService.Validate(customer))
{
return Send400BadRequest();
}
customerService.Update(customer);
return Send200Ok();
}
2- 在内部调用更新验证并抛出异常。
public IActionResult UpdateCustomer(CustomerDto customer)
{
customerService.Update(customer);
return Send200Ok();
}
在客户服务中
public void Update(CustomerDto customer)
{
if (!Validate(customer)
throws new CustomValidationException("Customer is not valid");
//Apply update
}
我们已经有一个 ActionFilter 来处理 CustomValidationException,所以它会返回一个 BadRequest。
1) 优点 +不要使用异常来使用正在运行的流程
缺点 -控制器更胖,对每种情况都有更多的决定,它将决定哪个是输出
2) 优点 +操作更原子,所有逻辑都在服务内部。 +更容易测试 +每次使用该方法都会得到验证。
缺点 - 使用异常来管理流程。
哪个是更好的解决方案?
我真的需要论据来捍卫其中一个。
【问题讨论】:
-
我不会考虑增加 2 行代码使控制器 IMO 膨胀。
-
对我来说不是臃肿与否,更多的是决策不应该在控制器中
-
@Balder,在点击操作之前使用另一个操作过滤器进行验证。横切关注点和单一责任原则。
-
如果你有一个业务逻辑层和一个服务层,我更喜欢在业务逻辑层中保留所有的业务逻辑规则,包括业务逻辑验证,并使用服务层作为业务逻辑层的包装器。跨度>
标签: asp.net-mvc exception asp.net-web-api exception-handling controller