问题描述
我想将对所有API控制器的请求限制为重定向到JSON路径.我想使用重定向,因为URL也应根据响应进行更改.
一种选择是使用before_filter
,它将请求重定向到相同的操作,但强制使用JSON格式.该示例尚不可用!
I would like to restrict requests to all API controllers to being redirected to the JSON path. I would like to use a redirect since also the URL should change according to the response.
One option would be to use a before_filter
which redirects the request to the same action but forces the JSON format. The example is not working yet!
# 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
另一种选择是在路由设置中限制格式.
Another option would be to restrict the format in the routes settings.
# routes.rb
MyApp::Application.routes.draw do
namespace :api, defaults: { format: 'json' } do
namespace :v1 do
resources :posts
end
end
end
我希望所有请求最终都成为JSON请求:
I want all request to end up as a JSON request:
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请求.
Setting a default in your routes won't turn all requests into a JSON request.
您要确保要呈现的内容是JSON响应
What you want is to make sure that whatever you're rendering is a JSON response
除了您需要执行此操作之外,您几乎都在第一个选项中拥有了它
You pretty much had it in the first option except you need to do this
before_filter :set_default_response_format
private
def set_default_response_format
request.format = :json
end
这将在您的Base API控制器下进行,以便在执行实际操作时,格式始终为JSON.
That would go under your Base API controller so that when it gets to your actual action the format will always be JSON.
这篇关于Rails:将API请求限制为JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!