强制所有收到的请求 Content-Type 为 JSON [英] Force all received requests Content-Type to JSON
问题描述
我实际上正在开发一个使用 Rails 4 的 API.如果客户端没有在 中指定媒体类型,我想将请求的
标题.Content-Type
设置为 JSON内容类型
I'm actually working on an API which uses Rails 4. I would like to set the Content-Type
of a request to JSON if the client does not specify a media type in Content-Type
header.
为了获得这种行为,我尝试在我的 ApplicationController
中添加以下 before_action
:
In order to get that behaviour I tried to add the following before_action
in my ApplicationController
:
def set_request_default_content_type
request.format = :json
end
在我的 RegistrationsController#create
方法中,我有一个断点来检查是否一切正常.好吧,request.format
技巧不起作用,尽管值设置为 application/json
似乎控制器(或 Rails 内部)不考虑接收到的请求的内容类型为 JSON.
In my RegistrationsController#create
method I have a breakpoint to check if everything is working. Well, the request.format
trick does not work, despite the value is set to application/json
it seems that the controller (or Rails internals) do not consider the received request's Content-Type as JSON.
我用以下正文(没有内容类型)做了一个 POST 请求:
I did a POST request with the following body (and no Content-Type) :
{"user" : {"email":"foobar@mail.net","password":"foobarfoo"}}
通过使用 Pry 进行调试,我看到:
By debugging with Pry I see that :
[2] api(#<V1::RegistrationsController>) _ request.format.to_s
=> "application/json"
[3] api(#<V1::RegistrationsController>) _ params
=> {
"action" => "create",
"controller" => "v1/registrations"
}
这意味着 Rails 没有考虑我的 request.format 配置了 Mime::JSON
的请求,而是使用了 Mime::ALL
,所以它没有'不解析请求的 JSON 正文.:(
It means that Rails did not have considered my request with the request.format configured with Mime::JSON
, but instead with Mime::ALL
and so it didn't parse the request's JSON body. :(
推荐答案
检查这个 SO answer.它使用 constraints
如下
Check this SO answer. It uses constraints
as follows
defaults format: :json do
# your v1/registration route here
end
这篇关于强制所有收到的请求 Content-Type 为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!