Content-Type
我实际上正在开发一个使用 Rails 4 的 API 。如果客户端未在标头中指定媒体类型,我想将请求设置为 JSON Content-Type
。
为了获得这种行为,我尝试before_action
在我的中添加以下内容ApplicationController
:
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
and 所以它没有解析请求的 JSON 正文。:(