规则是 Controller 不应该有业务逻辑,相反他们应该将它委托(delegate)给服务。但是当我们这样做时,我们无法处理所有可能的情况并返回适当的 HTTP 响应。
让我们看一个例子。假设我们正在构建某种社交网络,我们需要创建一个端点来对帖子进行评级(喜欢或不喜欢)。
首先让我们看一个示例,我们将逻辑委托(delegate)给服务,这是我们的 Controller 操作:
public IActionResult Rate(long postId, RatingType ratingType)
{
var user = GetCurrentUser();
PostRating newPostRating = _postsService.Rate(postId, ratingType, user);
return Created(newPostRating);
}
你觉得这有什么问题吗?如果没有给定 id 的帖子怎么办,我们将如何返回未找到的响应?如果用户无权对帖子进行评分怎么办,我们将如何返回禁止回复?
PostsService.Rate
只能返回一个新的PostRating
,其他情况呢?好吧,我们可以抛出一个异常,我们需要创建很多自定义异常,以便我们可以将它们映射到适当的 HTTP 响应。我不喜欢为此使用异常,我认为有更好的方法来处理这些情况而不是异常。因为我认为帖子不存在和用户没有权限的情况一点也不异常(exception),它们只是正常情况,就像成功评级帖子一样。
我的建议是在 Controller 中处理该逻辑。因为在我看来,无论如何,这应该是 Controller 的责任,在执行操作之前检查所有权限。所以我会这样做:
public IActionResult Rate(long postId, RatingType ratingType)
{
var user = GetCurrentUser();
var post = _postsRepository.GetByIdWithRatings(postId);
if (post == null)
return NotFound();
if (!_permissionService.CanRate(user, post))
return Forbidden();
PostRating newPostRating = new PostRating
{
Post = post,
Author = user,
Type = ratingType
};
_postRatingsRepository.Save(newPostRating);
return Created(newPostRating);
}
我认为这是应该完成的方式,但我敢打赌有人会说这对 Controller 来说逻辑太多,或者您不应该在其中使用存储库。
如果您不喜欢在 Controller 中使用存储库,那么您会在哪里放置一个获取或保存帖子的方法?在役?所以会有 PostsService.GetByIdWithRatings
和 PostsService.Save
除了调用 PostsRepository.GetByIdWithRatings
和 PostsRepository.Save 什么都不做
。这是不必要的,只会导致样板代码。
更新: 也许有人会说使用 PostsService 检查权限,然后调用 PostsService.Rate。这很糟糕,因为它涉及更多不必要的数据库访问。例如,它可能是这样的:
public IActionResult Rate(long postId, RatingType ratingType)
{
var user = GetCurrentUser();
if(_postsService.Exists(postId))
return NotFound();
if(!_postsService.CanUserRate(user, postId))
return Forbidden();
PostRating newPostRating = _postsService.Rate(postId, ratingType, user);
return Created(newPostRating);
}
我什至需要进一步解释为什么这是不好的吗?
最佳答案
有很多方法可以处理这个问题,但最接近“最佳实践”方法的可能是使用结果类。例如,如果您的服务方法创建了一个评级,然后返回它创建的评级,那么您将返回一个对象,该对象封装了该评级以及其他相关信息,例如成功状态、错误消息(如果有的话)。
public class RateResult
{
public bool Succeeded { get; internal set; }
public PostRating PostRating { get; internal set; }
public string[] Errors { get; internal set; }
}
然后,你的 Controller 代码会变成这样:
public IActionResult Rate(long postId, RatingType ratingType)
{
var user = GetCurrentUser();
var result = _postsService.Rate(postId, ratingType, user);
if (result.Succeeded)
{
return Created(result.PostRating);
}
else
{
// handle errors
}
}
关于asp.net - 将业务逻辑与 Controller 解耦的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51860210/