Get Content Type of Request

2019-06-14 22:33发布

To find the incoming content type, docs say:

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

But I found by trial-and-error, that doesn't work, but this does:

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

So what's the most robust+portable way to do it?

6条回答
放荡不羁爱自由
2楼-- · 2019-06-14 22:49

You don't need to parse the content_type string, Rails has already done this for you. Just check:

request.format.symbol == :json
查看更多
别忘想泡老子
3楼-- · 2019-06-14 22:53

Another way of writing it:

request.format.json?
查看更多
在下西门庆
4楼-- · 2019-06-14 22:53

request.format == 'application/json'

查看更多
萌系小妹纸
5楼-- · 2019-06-14 23:01

For me the best way to check if incoming request is a json was:

    if request.content_type =~ /json/
查看更多
\"骚年 ilove
6楼-- · 2019-06-14 23:09

I would usually go for request.format and request.content_type for reading these header fields.

EDIT: found a bit more on this that might help: https://stackoverflow.com/a/1595453/624590

查看更多
Lonely孤独者°
7楼-- · 2019-06-14 23:12

No need to call #symbol since equals is overloaded:

request.format == :json
查看更多
登录 后发表回答