【发布时间】:2014-05-24 05:44:52
【问题描述】:
我实际上正在开发一个使用 Rails 4 的 API。如果客户端未在 Content-Type 标头中指定媒体类型,我想将请求的 Content-Type 设置为 JSON。
为了获得这种行为,我尝试在我的 ApplicationController 中添加以下 before_action :
def set_request_default_content_type
request.format = :json
end
在我的RegistrationsController#create 方法中,我有一个断点来检查一切是否正常。好吧,request.format 技巧不起作用,尽管该值设置为 application/json,但控制器(或 Rails 内部)似乎不将接收到的请求的 Content-Type 视为 JSON。
我使用以下正文(并且没有 Content-Type)进行了 POST 请求:
{"user" : {"email":"foobar@mail.net","password":"foobarfoo"}}
通过使用 Pry 进行调试,我发现:
[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 正文。 :(
【问题讨论】:
-
我认为你需要在你身上使用wrap_parameters()
ActionController -
ActionController::ParamsWrapper默认启用 json 格式。但它不起作用。目前我不使用 MetalController,而是使用带有标准控制器的经典 Rails 架构。
标签: ruby-on-rails ruby api ruby-on-rails-4 rails-api