获取内容请求类型

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

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

但我通过反复试验发现,这不起作用,但这样做:

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

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

我通常会使用request.formatrequest.content_type来读取这些头字段。

编辑 :发现这可能有所帮助: https : //stackoverflow.com/a/1595453/624590

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

 request.format.symbol == :json 

另一种写作方式:

 request.format.json? 

由于equals重载,因此无需调用#symbol:

 request.format == :json 

request.format ==’application / json’

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

  if request.content_type =~ /json/