我希望只有客户端要求的所有请求Accept
和Content-Type
标头才能强制执行JSON。当然,总是以JSON回应!
我尝试使用以下respond_to
和before_action
过滤器:
respond_to :json
before_action { headers["Content-Type"] = Mime::JSON.to_s }
before_action { request.format = 'json' }
但是,当我尝试在POST
路由上执行login
请求时,没有Accept
和Content-Type
,相关控制器仍将请求处理为{{1} }}。如果用户设置了另一个*/*
,例如Content-Type
,则仍会使用此application/html
代替Content-Type
。
application/json
有没有办法在没有太多肮脏的黑客的情况下做到这一点?
谢谢,
微米。
答案 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