Ruby-on-rails 获取请求的内容类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15227145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:32:49  来源:igfitidea点击:

Get Content Type of Request

ruby-on-railshttprestruby-on-rails-3.1mime

提问by mahemoff

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?

那么最健壮+便携的方法是什么?

回答by DRobinson

I would usually go for request.formatand request.content_typefor reading these header fields.

我通常会去request.formatrequest.content_type读取这些字段。

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

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

回答by Kent Mewhort

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

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

request.format.symbol == :json

回答by montrealmike

Another way of writing it:

另一种写法:

request.format.json?

回答by Tim Scott

No need to call #symbol since equals is overloaded:

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

request.format == :json

回答by amn

request.format == 'application/json'

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

回答by Leszek

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

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

    if request.content_type =~ /json/