我想限制对所有 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
...
您会推荐哪种策略?
在路由中设置默认值不会将所有请求转换为 JSON 请求。
您想要的是确保您渲染的任何内容都是 JSON 响应
你在第一个选项中几乎已经有了它,除了你需要这样做
before_filter :set_default_response_format
private
def set_default_response_format
request.format = :json
end
这将在您的 Base API 控制器下进行,这样当它到达您的实际操作时,格式将始终为 JSON。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)