【问题标题】:Disable Content-Type header in Rails / Rack在 Rails / Rack 中禁用 Content-Type 标头
【发布时间】:2014-03-18 07:46:54
【问题描述】:

我正在编写一个返回 HTTP 102(处理)的 Rails 控制器方法:

render nothing: true, status: :processing, content_type: nil

但是,我得到了一个Rack::Lint::LintError(通过独角兽):

Content-Type header found in 102 response, not allowed

我还没有找到任何明显的方法来禁用此标头。将其归入response.headers,将其从哈希中删除,将response.content_type 归零,在渲染选项中将其作为nil 传递,似乎都没有任何效果。

我在https://stackoverflow.com/a/4032459/3712 中读到,如果缺少标题,添加标题的不是 Rails,而是 Rack。然而,抱怨的是 Rack 本身!

如何禁用标题添加?

或者我最好禁用 Rack linting?

或者我还缺少什么?

PS:我检查了我正在使用的版本(1.4.5)的机架源:没有为没有实体主体的状态代码添加 Content-Type 标头,根据rack-1.4.5/lib/rack/utils.rb,它包括所有 1xx 状态代码.所以我认为实际上添加标题的不是 Rack。

PPS:经过几个小时的调试,罪魁祸首是响应上的to_a调用,它在actionpack-3.2.11/lib/action_dispatch/http/response.rb中调用assign_default_content_type_and_charset!

def assign_default_content_type_and_charset!
  return if headers[CONTENT_TYPE].present?

  @content_type ||= Mime::HTML
  @charset      ||= self.class.default_charset

  type = @content_type.to_s.dup
  type << "; charset=#{@charset}" unless @sending_file

  headers[CONTENT_TYPE] = type
end

如果没有一些侵入性的黑客攻击,我似乎无能为力,比如添加特殊用途的中间件,或者猴子补丁动作包的ActionDispatch::Response

【问题讨论】:

    标签: ruby-on-rails http-headers content-type rack


    【解决方案1】:

    为了解决这个问题,我添加了一个新的 Rails 中间件类:

    class RemoveContentType
      def initialize(app)
        @app = app
      end
    
      def call(env)
        status, headers, body = @app.call(env)
        # ActionDispatch::Response always inserts Content-Type header
        # Remove it for status codes that don't allow it
        headers.delete('Content-Type') if (100..199).include?(status.to_i)
        return [status, headers, body]
      end
    end
    

    application.rb中如此配置:

    config.middleware.use "::RemoveContentType"
    

    为我的 102 用例工作。可以更新解决方案以处理 1xx 以外的其他状态代码。

    【讨论】:

    • 我很惊讶很少有人遇到这个问题。
    猜你喜欢
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    相关资源
    最近更新 更多