加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Rails / Rack中禁用Content-Type标头

发布时间:2020-12-17 02:40:19 所属栏目:百科 来源:网络整理
导读:我正在编写一个返回HTTP 102(处理)的Rails控制器方法: render nothing: true,status: :processing,content_type: nil 但是,我得到了一个Rack :: Lint :: LintError(通过独角兽): Content-Type header found in 102 response,not allowed 我没有找到任何明
我正在编写一个返回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本身就是在抱怨!

如何禁用标题添加?

或者我最好禁用机架linting?

或者还有其他我想念的东西?

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

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

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

如果没有一些侵入式的黑客行为,比如添加特殊用途的中间件,或monkeypatching actionpack的ActionDispatch :: Response,我似乎没有太多可以做到这一点.

解决方法

为了解决这个问题,我添加了一个新的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,body]
  end
end

因此在application.rb中配置:

config.middleware.use "::RemoveContentType"

适用于我的102用例.可以更新解决方案以处理超过1xx的其他状态代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读