仅将请求Accept-Type和Content-Type强制实施为JSON

时间:2014-06-14 08:15:28

标签: ruby-on-rails ruby ruby-on-rails-4 rails-api

我希望只有客户端要求的所有请求AcceptContent-Type标头才能强制执行JSON。当然,总是以JSON回应!

我尝试使用以下respond_tobefore_action过滤器:

respond_to :json

before_action { headers["Content-Type"] = Mime::JSON.to_s }
before_action { request.format = 'json' }

但是,当我尝试在POST路由上执行login请求时,没有AcceptContent-Type,相关控制器仍将请求处理为{{1} }}。如果用户设置了另一个*/*,例如Content-Type,则仍会使用此application/html代替Content-Type

application/json

有没有办法在没有太多肮脏的黑客的情况下做到这一点?

谢谢,

微米。

1 个答案:

答案 0 :(得分:2)

您可以通过before_filter限制内容类型,如下所示:

class ApplicationController < ActionController::Base

    before_filter :restrict_content_type

    private
    def restrict_content_type
        render json: {msg:  'Content-Type must be application/json'}, status: 406 unless request.content_type == 'application/json'
    end
end