1

我只想将所有请求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,没有Acceptand Content-Type,相关控制器仍将请求处理为*/*. 如果用户设置了另一个Content-Type,例如application/html,它仍然使用 thisContent-Type而不是application/json.

Started POST "/login" for 127.0.0.1 at 2014-06-14 10:05:16 +0200
Processing by V1::AuthenticationsController#create as */*
ActionController::ParameterMissing(param is missing or the value is empty: user):

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

谢谢,

M。

4

1 回答 1

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
于 2014-12-05T17:29:34.517 回答