使用 Content-Type 对 HTTP GET 的正确响应

Correct response for HTTP GET with a Content-Type

使用 Content-Type 的 HTTP GET 的正确响应是什么?我们应该以错误响应还是应该忽略 Content-Type 并处理请求?

根据RFC 7231 section 3.1.1.5

A sender that generates a message containing a payload body SHOULD generate a Content-Type header field in that message unless the intended media type of the enclosed representation is unknown to the sender. If a Content-Type header field is not present, the recipient MAY either assume a media type of "application/octet-stream" ([RFC2046], Section 4.5.1) or examine the data to determine its type.

因此,请求中任何具有“body”有效负载的内容都应传入 Content-type。

GET、DELETE、HEAD、OPTIONS 通常没有这样的负载。但是might。所以根据请求方式来判断是否有body并不是一个很安全的方式。

如果您的服务器收到一个 GET,并且它有一个 body,并且 body 不是 application/octet-stream 那么它应该有一个 Content-Type header.当您收到这样的请求时,可以安全地发回 406 - Not Accepted

另一方面,如果您的服务器不处理 GET 上的 body,那么也可以安全地发回 406 - Not Accepted