强制所有收到的请求Content-Type为JSON
我实际上正在使用一个使用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。
我使用以下正文进行了POST请求(并且没有Content-Type):
{"user" : {"email":"foobar@mail.net","password":"foobarfoo"}}
通过Pry调试我看到:
[2] api(#) _ request.format.to_s => "application/json" [3] api(#) _ params => { "action" => "create", "controller" => "v1/registrations" }
这意味着Rails没有考虑我的请求,使用Mime::JSON
配置了request.format,而是使用Mime::ALL
,因此它没有解析请求的JSON主体。 🙁
class V1::RegistrationsController < ApplicationController respond_to :json end
制作默认的响应格式json
您可以在respond_to
块中定义any
类型响应,这不会限制您的控制器在请求uri以.json
结尾时响应,它还可以减轻您明确定义响应类型的速度,并且将独立于请求内容类型保持响应如你所愿,例如:
respond_to do |format| format.any {render :json => {foo: 'bar'}} end
您应该能够使用路由设置默认格式: http : //guides.rubyonrails.org/routing.html#defining-defaults
resources :registrations, ... defaults: { format: 'json' }
另请参阅: 如何在Rails中设置路由的默认格式? 格式换一个路由function于导轨?answertab =活性#制表顶
也许有兴趣:
- http://apidock.com/rails/ActionController/MimeResponds/respond_with
- http://apidock.com/rails/ActionController/MimeResponds/respond_to (本页底部的有趣评论)
Rails在包含“,/”或“/”时忽略accept头,并返回HTML(如果是xhr请求,则返回JS)。
这是设计为从浏览器访问时始终返回HTML。
这不遵循mime类型协商规范,但它是绕过带有错误接受标头的旧浏览器的唯一方法。 他们接受了第一个mime类型的标题为image / png或text / xml。