Ruby on rails Rails-根据API版本向响应添加自定义头
我想做的很简单。Rails REST API有多个版本。因此,有如下路线:Ruby on rails Rails-根据API版本向响应添加自定义头,ruby-on-rails,ruby,rest,http-headers,rack,Ruby On Rails,Ruby,Rest,Http Headers,Rack,我想做的很简单。Rails REST API有多个版本。因此,有如下路线: http://www.example.com/v1/user.json http://www.example.com/v2/user.json http://www.example.com/v3/user.json 我要做的是根据请求的API版本端点向响应添加自定义http头 在我的config/application.rb文件中,我尝试了: config.action_dispatch.default_header
http://www.example.com/v1/user.json
http://www.example.com/v2/user.json
http://www.example.com/v3/user.json
我要做的是根据请求的API版本端点向响应添加自定义http头
在我的config/application.rb文件中,我尝试了:
config.action_dispatch.default_headers.merge!('my_header_1' => 'my_value_1', 'my_header_2' => 'my_value_2')
我在config/routes.rb文件中也尝试过:
scope path: "v1", controller: :test do
get "action_1" => :action_1
get "action_2" => :action_2
Rails.application.config.action_dispatch.default_headers.merge!('my_header_1' => 'my_value_1', 'my_header_2' => 'my_value_2')
end
但这两个代码段都将自定义头附加到响应中,而与API版本端点无关
我认为我可以编写一个中间件来检查请求url,并在此基础上附加响应头,但这听起来有点黑客
有没有更好的方法来实现这一点?最好通过配置或一些核心代码?在控制器上执行操作之前使用
怎么样?我想每个API版本都有自己的控制器?这样,您可以执行以下操作:
class API::V1::BaseController < ApplicationController
before_action :set_headers
protected
def set_headers
response.headers['X-Foo'] = 'V1'
end
end
class API::V1::BaseController
如果操作前的不起作用,请尝试在操作前的prepend\u
。