获取请求的内容类型

问题描述 投票:0回答:8

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

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

但是我通过反复试验发现,这行不通,但是这个可以:

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

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

ruby-on-rails http rest ruby-on-rails-3.1 mime
8个回答
44
投票

我通常会使用

request.format
request.content_type
来读取这些标头字段。

编辑:找到更多可能有帮助的信息:https://stackoverflow.com/a/1595453/624590


26
投票

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

request.format.symbol == :json

24
投票

另一种写法:

request.format.json?

12
投票

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

request.format == :json

3
投票

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

    if request.content_type =~ /json/

2
投票

request.format == 'application/json'


2
投票

这里需要重点理解。参考号Rails 6.x 仅包含 api 项目

您必须确定为什么您想要

request.content_type
request.headers['Content-Type']
?下面解释...

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

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

因此,如果 API(服务或服务器)想要请求

application/json
中的数据,那么您使用 request.content_type 或
request.headers['Content-Type']

是正确的

0
投票

我认为所有之前的答案都有点误导,尽管其中一些答案是正确的,而且最精确的答案的格式不足以突出问题。其他人没有明确提到有两个不同的标题,所以建议使用

request.format
的答案会让你处于检查错误的非常危险的境地。

首先,Rails(使用 >=4.2 进行验证)将这些标头视为不区分大小写

request.headers['CONTENT_TYPE'] # "application/json"
request.headers['Content-type'] # "application/json"
request.headers['Content-Type'] # "application/json"

您的问题可能与以前的 Rails 版本有关,因为它是在 2013 年提出的。

为了避免弄乱标头,最好使用专用方法:

方法 标题 意义
request.content_type
Content-Type
客户发送给您的内容
request.format
Accept
客户对您的期望
© www.soinside.com 2019 - 2024. All rights reserved.