Ruby-on-rails 你如何添加自定义http标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16654052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:00:39  来源:igfitidea点击:

How do you add a custom http header?

ruby-on-railshttphttp-headers

提问by Jngai1297

I'm looking to add custom http headers to a Ruby on Rails app that is currently hosted on Heroku.

我希望将自定义 http 标头添加到当前托管在 Heroku 上的 Ruby on Rails 应用程序。

回答by Lazarus Lazaridis

Use:

用:

response.headers['HEADER NAME'] = 'HEADER VALUE'

either in a specific method or to a before_filter method of your application controller depending on whether you need this to be added in a specific or to all of your responses.

在特定方法中或应用程序控制器的 before_filter 方法中,具体取决于您是否需要将其添加到特定或所有响应中。

UPDATE for Rails 5 - February 24th, 2018

Rails 5 更新 - 2018 年 2 月 24 日

As noted by @BrentMatzelle in the comments, for Rails 5:

正如@BrentMatzelle 在评论中指出的,对于Rails 5

response.set_header('HEADER NAME', 'HEADER VALUE')

回答by Shakil

In rails 5, the following solution works (in action methods)

在 rails 5 中,以下解决方案有效(在操作方法中)

response.set_header("Header-Name", "Header value")

Reference: edgeapi

参考:edgeapi

回答by Franklin Yu

In Rails 3 or above, simply

在 Rails 3 或更高版本中,只需

headers['Header-Name'] = 'header value'

works in controllers. This is even therecommended way; according to the documentation,

在控制器中工作。这甚至推荐的方式;根据文档

Response is mostly a Ruby on Rails framework implementation detail, and should never be used directly in controllers. Controllers should use the methods defined in ActionController::Baseinstead. For example, if you want to set the HTTP response's content MIME type, then use ActionController::Base#headersinstead of Response#headers.

响应主要是 Ruby on Rails 框架实现细节,不应直接在控制器中使用。控制器应该使用 中定义的方法ActionController::Base。例如,如果要设置 HTTP 响应的内容 MIME 类型,则使用ActionController::Base#headers代替Response#headers

And this is still true in Rails 6.0.

这仍是Rails的6.0属实

回答by maniempire

In rails 4, set the response headers in the application.rb or respective environment files. Once you done that, you can override the header value wherever you required in the controller. Refer this urlfor more details.

在 rails 4 中,在 application.rb 或相应的环境文件中设置响应头。完成此操作后,您可以在控制器中需要的任何位置覆盖标头值。有关更多详细信息,请参阅此网址

回答by Slava Zharkov

In rails 4 works following:

在 rails 4 中工作如下:

class API::V1::BaseController 
  after_action :set_version_header

  protected
    def set_version_header
        response.headers['X-ComanyName-Api-Version'] = 'V1'
    end
end