【发布时间】:2020-08-17 18:14:34
【问题描述】:
假设我有以下使用服务层的 rest api 端点:
[HttpGet("id")]
public async Task<IActionResult> GetById(int id)
{
var entity = _someService.GetById(id);
return Ok(entity);
}
在服务方法中,用户没有权限访问该实体:
public Entity GetById(int id)
{
var entity = _repository.Get(id)
if(entity.OwnerId != CurrentUserId) // true
{
...
}
}
或者它根本不存在:
public Entity GetById(int id)
{
var entity = _repository.Get(id)
if(entity is null) // true
{
...
}
}
处理此类情况并通过在响应中设置合适的状态代码让用户知道出现问题的最佳方法是什么?
我能想到的是定义结果类,其中还包含请求结果,例如:
public class RequestResult<T>
{
public T Result {get; set;}
public int StatusCode {get; set;} // 200, 404, 403 ...
}
或者(我个人更喜欢)定义并抛出 ForbiddenException 或 NotFoundException 并通过设置合适的响应状态码在 ExceptionHandlingMiddleware 中处理这些。
【问题讨论】:
标签: c# asp.net-core architecture