只响应rails中的json

av5*_*501 14 ruby-on-rails ruby-on-rails-3

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

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

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

关于我如何做这两个动作的任何想法?

pdu*_*ler 35

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

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

例:

class SomeController < ApplicationController
  respond_to :json


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

    respond_with @record
  end
end
Run Code Online (Sandbox Code Playgroud)

另一种方法是添加一个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
Run Code Online (Sandbox Code Playgroud)

  • `respond_to`方法已从Rails 4中删除,如果你想使用它,请使用[responders gem](https://github.com/plataformatec/responders). (2认同)

Ere*_*bih 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
Run Code Online (Sandbox Code Playgroud)