Get Content Type of Request

喜欢而已 提交于 2019-12-08 14:32:25

问题


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?


回答1:


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




回答2:


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

request.format.symbol == :json



回答3:


Another way of writing it:

request.format.json?



回答4:


No need to call #symbol since equals is overloaded:

request.format == :json



回答5:


request.format == 'application/json'




回答6:


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

    if request.content_type =~ /json/


来源:https://stackoverflow.com/questions/15227145/get-content-type-of-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!