HTTP 状态代码 - 401/NotAuthorized 与 404/NotFound 与 400/BadRequest

HTTP Status Codes - 401/NotAuthorized vs 404/NotFound vs 400/BadRequest

我有属于 Company 实体的 Widget 实体。 Companies 和 Widgets 之间存在一对多的关系。

这是我第一次访问 Get 方法:

[Route("MyApi/Companies/{companyId}/WidgetAdministration/[controller]")]
[HttpGet("{widgetId}")]
public async Task<ActionResult<WidgetDTO>> GetWidget([FromRoute] int companyId, [FromRoute]int widgetId)
{
    WidgetDTO widgetDto = await _myContext.Widgets
        .Where(w => w.CompanyId == companyId && w.WidgetId == widgetId)
        .AsNoTracking()
        .ProjectTo<WidgetDTO>(_mapper.ConfigurationProvider)
        .FirstOrDefaultAsync();

    if (widgetDto == null)
    {
        return NotFound();
    }
    else
    {
        return Ok(widgetDto);
    }
}

如果关联到 "Company 1" 的用户请求 "Company 1 Widget 55",但 "Widget 55" 属于 "Company 2",我应该如何 return?

404/NotFound - 因为 "Widget 55" 属于 "Company 2",所以上面的 LINQ 语句不会找到任何东西,即使 "Widget 55" 真的确实存在。

401/NotAuthorized - 由于 "Widget 55" 不属于 "Company 1",因此 "Company 1" 无权查看它。

400/BadRequest - 这只是一个错误的请求,因为 Widget 和 Company 不匹配。

顺便说一句,谁能推荐一个好的资源来帮助我处理其他类似的情况?

我会 return 404 有两个原因:

  1. 在我看来,404 不是指 Widget/55,而是指整个资源 URI:Company/1/Widget/55。该资源不存在。
  2. 403 阻止公司 1 查看公司 2 的小部件,但它确实暴露了 Widget/55 存在的事实。这可能会或可能不会被您接受。 According to the World Wide Web Consortium (W3C)、"if the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead."