我想限制对所有 API Controller 的请求被重定向到 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
...
您会推荐哪种策略?
最佳答案
在您的路由中设置默认值不会将所有请求都转换为 JSON 请求。
您想要确保呈现的内容是 JSON 响应
除了你需要这样做之外,你几乎在第一个选项中就有了它
before_filter :set_default_response_format
private
def set_default_response_format
request.format = :json
end
这将在您的 Base API Controller 下进行,因此当您执行实际操作时,格式将始终为 JSON。
关于ruby-on-rails - rails : Restrict API requests to JSON format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14664049/