gpt4 book ai didi

ruby-on-rails - 在 Rails/Rack 中禁用 Content-Type header

转载 作者:行者123 更新时间:2023-12-05 00:26:39 26 4
gpt4 key购买 nike

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

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

但是,我得到了一个 Rack::Lint::LintError (通过 unicorn ):
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)的 Rack 源:没有为没有实体主体的状态代码添加 Content-Type header ,根据 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, headers, body]
end
end

application.rb 中如此配置:
config.middleware.use "::RemoveContentType"

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

关于ruby-on-rails - 在 Rails/Rack 中禁用 Content-Type header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com