【问题标题】:404 Not Found or Bad Request?404 Not Found 或错误请求?
【发布时间】:2015-01-14 02:47:31
【问题描述】:

假设我们有以下 REST 调用:

GET api/companies/5 

(获取 id 为 5 的公司)

如果公司 '5' 不存在,我们通常会返回 404 Not Found 响应。

但是现在,让我们接听这个电话:

GET api/companies/5/invoices/10 

(从公司 5 获取发票 10)

现在,如果公司 '5' 不存在,我们还返回404 Not Found 吗?或者仅在无法找到最外层资源(在这种情况下为发票 10)时才返回 404。

Bad Request 可能是更好的选择吗?

【问题讨论】:

  • 最好有一个 404 但使用自定义错误消息处理,向用户隐藏丑陋的错误总是更好
  • 从技术上讲,应该是 404。但是响应正文可能包含任何内容。全面响应将推动下一步。

标签: rest asp.net-web-api http-status-code-404 asp.net-web-api2 api-design


【解决方案1】:

404 是您最好的回应。根据 HTTP RFC,http://www.ietf.org/rfc/rfc2616.txt

400 错误请求意味着:

由于语法错误,服务器无法理解请求。

然而,404 状态:

服务器没有找到任何匹配 Request-URI 的东西。

整个 URI 是您的资源标识符,您找不到与该特定标识符匹配的资源。

【讨论】:

    【解决方案2】:

    404 可能会导致混淆 - 是资源丢失还是实际 URL 不正确?

    我个人会选择422 代码:

       The 422 (Unprocessable Entity) status code means the server
       understands the content type of the request entity (hence a
       415(Unsupported Media Type) status code is inappropriate), and the
       syntax of the request entity is correct (thus a 400 (Bad Request)
       status code is inappropriate) but was unable to process the contained
       instructions.  For example, this error condition may occur if an XML
       request body contains well-formed (i.e., syntactically correct), but
       semantically erroneous, XML instructions.
    

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多