Tag: restriction

Rails:将API请求限制为JSON格式

我想限制所有API控制器的请求被重定向到JSON路径。 我想使用重定向,因为URL也应根据响应而改变。 一种选择是使用before_filter将请求重定向到相同的操作但强制JSON格式。 这个例子还没有用! # base_controller.rb class Api::V1::BaseController < InheritedResources::Base before_filter :force_response_format respond_to :json def force_response_format redirect_to, params[:format] = :json end end 另一种选择是限制路线设置中的格式。 # routes.rb MyApp::Application.routes.draw do namespace :api, defaults: { format: ‘json’ } do namespace :v1 do resources :posts end end end 我希望所有请求最终都是JSON请求: http://localhost:3000/api/v1/posts http://localhost:3000/api/v1/posts.html http://localhost:3000/api/v1/posts.xml http://localhost:3000/api/v1/posts.json … 你会推荐哪种策略?