只响应rails中的json

时间:2013-01-29 09:40:26

标签: ruby-on-rails ruby-on-rails-3

在我的rails应用程序中,只有json,我想发送一个406代码,只要有人调用我的rails应用程序,接受标头设置为除application / json之外的任何东西。当我将内容类型设置为除application / json

之外的任何内容时,我还希望它发送415

我的控制器有respond_to:json穿上它们。我只在所有动作中渲染json。但是,如何确保为所有其他接受标头/内容类型调用的所有调用返回错误代码406/415,并将格式设置为除json之外的任何内容。

EG。如果我的资源是书籍/ 1我想允许 books / 1.json或books / 1 with application / json in accept header and content type

关于我如何做这两项行动的任何想法?

3 个答案:

答案 0 :(得分:35)

基本上,您可以通过两种方式限制回复。

首先,您的控制器有respond_to。如果对格式的请求未定义,则会自动触发406 Not Acceptable

示例:

class SomeController < ApplicationController
  respond_to :json


  def show
    @record = Record.find params[:id]

    respond_with @record
  end
end

另一种方法是添加before_filter来检查格式并做出相应的反应。

示例:

class ApplicationController < ActionController::Base
  before_filter :check_format


  def check_format
    render :nothing => true, :status => 406 unless params[:format] == 'json' || request.headers["Accept"] =~ /json/
  end
end

答案 1 :(得分:9)

您可以使用ApplicationController中的before_filter

before_filter :ensure_json_request

def ensure_json_request
  return if params[:format] == "json" || request.headers["Accept"] =~ /json/
  render :nothing => true, :status => 406
end

答案 2 :(得分:-1)

on rails 4.2+ respond_to已被删除,因此除非您想为此导入完整的响应者宝石,否则最好的选择是自己动手。这就是我在rails 5 api中使用的内容:

    class ApplicationController < ActionController::API
      before_action :force_json

      private
      def force_json
        # if params[_json] it means request was parsed as json 
        # if body.read.blank? there was no body (GET/DELETE) so content-type was meaningless anyway
        head :not_acceptable unless params['_json'] || request.body.read.blank?
      end
    end