当请求缺少必需的 cookie 时,适当的 HTTP 状态代码是什么?

What's the appropriate HTTP status code when the request is missing a required cookie?

我有一个 API 端点,请求应该有一个 cookie(不是身份验证)。 return 如果不存在,正确的 HTTP 状态代码是什么?

我假设 400 错误请求是最好的。

你的问题没有提供太多细节,但我想 400 (Bad Request) 是一个不错的选择:

6.5.1. 400 Bad Request

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

但是,根据您的要求,您还可以考虑 WebDAV 规范中定义的 422(无法处理的实体)状态代码,它只是 HTTP 协议的扩展:

11.2. 422 Unprocessable Entity

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.


请记住在响应负载中提供一个很好的描述,解释请求中缺少的内容。

对于这种情况,我会考虑使用 403 forbidden 状态代码 - 其他一切都很好,但请求缺少 cookie。要从链接的参考中复制其详细信息:

The server understood the request but refuses to authorize it.

If authentication credentials were provided in the request, the server considers them insufficient to grant access

状态401 unauthorized 用于请求缺少身份验证凭据的情况。但是 401 还要求响应包含一个 WWW-Authenticate header 字段 。根据问题,请求应该有一个 cookie 但没有,这不是身份验证的问题。

Status 400 是客户端请求错误的时候,这对于 OP 描述的场景可能有点误导。

Status 422 可能是合适的,但我认为,有点太笼统了,因为它意味着 一切正常,但服务器无法处理请求.