仅响应 rails 中的 json [英] respond to only json in rails
问题描述
在我只有 json 的 rails 应用程序中,每当有人调用我的 rails 应用程序时,我想发送一个 406 代码,并且接受标头设置为除 application/json 之外的任何内容.当我将内容类型设置为除 application/json 之外的任何内容时,我还希望它发送 415
In my rails app which is json only, I want to send a 406 code whenever someone calls my rails app with accept header set to anything except application/json. I also want it to send a 415 when I get the content type set to anything except application / json
我的控制器上有 response_to :json .我只在所有操作中渲染 json.但是,我如何确保为所有其他接受标头/内容类型调用的所有调用返回错误代码 406/415,并且格式设置为除 json 之外的任何内容.
My controllers have respond_to :json put on them. I only render json in all actions. However how do I ensure that I return error code 406/415 for all calls for anything that is called for all other accept headers/content-type and with format set to anything except json.
例如.如果我的资源是书籍/1 我想允许接受标题和内容类型的books/1.json 或books/1 带有application/json
Eg. If I my resource is books/1 I want to allow books/1.json or books/1 with application/json in accept header and content type
关于如何执行这两个操作的任何想法?
Any ideas on how I can do these two actions?
推荐答案
基本上,您可以通过两种方式限制您的回复.
Basically, you can limit your responses in two ways.
首先,您的控制器有 respond_to
.如果请求未定义的格式,这将自动触发 406 Not Acceptable
.
First, there is respond_to
for your controllers. This would automatically trigger a 406 Not Acceptable
if a request for a format is made which is not defined.
示例:
class SomeController < ApplicationController
respond_to :json
def show
@record = Record.find params[:id]
respond_with @record
end
end
另一种方法是添加一个 before_filter
来检查格式并做出相应的反应.
The other way would be to add a before_filter
to check for the format and react accordingly.
示例:
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
这篇关于仅响应 rails 中的 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!