[英]respond to only json in rails
在我的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
關於我如何做這兩個動作的任何想法?
基本上,您可以通過兩種方式限制您的回復。
首先,您的控制器有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
你可以在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
在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.