23

要查找传入的内容类型,文档说

 request.headers["Content-Type"] # => "text/plain"

但是我通过反复试验发现,这是行不通的,但这确实:

 request.headers["CONTENT_TYPE"]=='application/json'

那么最强大+便携的方法是什么?

4

7 回答 7

42

我通常会去request.format阅读request.content_type这些标题字段。

编辑:在这方面发现了更多可能有帮助的信息:https ://stackoverflow.com/a/1595453/624590

于 2013-03-05T15:14:54.433 回答
25

您不需要解析 content_type 字符串,Rails 已经为您完成了这项工作。只需检查:

request.format.symbol == :json
于 2014-09-29T21:17:44.043 回答
18

另一种写法:

request.format.json?
于 2017-03-22T18:47:00.690 回答
11

无需调用 #symbol,因为 equals 已重载:

request.format == :json
于 2015-11-17T23:06:59.310 回答
2

对我来说,检查传入请求是否为 json 的最佳方法是:

    if request.content_type =~ /json/
于 2014-02-26T11:59:10.573 回答
2

request.format == '应用程序/json'

于 2017-11-15T07:17:25.157 回答
0

严重需要重点了解这里。参考。Rails 6.x with api only project

您必须确定为什么要 request.content_type 或 request.headers['Content-Type'] ?下面解释...

  1. request.format OR request.headers['Accept'] 是客户端期望通过 API(服务或服务器)请求响应的格式。

  2. request.content_type OR request.headers['Content-Type'] 是 API(服务或服务器)期望来自请求的数据格式。

因此,如果 API(服务或服务器)想要在 application/json 中请求数据,那么您使用 request.content_type 或 request.headers['Content-Type'] 是正确的

于 2020-08-25T12:51:59.957 回答