在早期版本中,这会起作用:
ActionController::Renderers.add(:foo) do | data, options |
self.content_type = 'application/foo; bar=1'
end
在 4.2.4 中,这会导致 Content-Type 标题为空。但是,以下有效,即将 Content-Type header 设置为分配给 content_type 的字符串:
ActionController::Renderers.add(:foo) do | data, options |
self.content_type = 'application/foo'
end
我知道的另一种方法,在渲染上设置 content_type,似乎不再有结果,即
render('foo', content_type: 'application/foo')
不设置标题(不要介意尝试 application/foo; bar=1。)
最佳答案
首先看一下文档(2.2.13.1节):
http://guides.rubyonrails.org/layouts_and_rendering.html#using-render
他们在那里给出的示例使用您的替代方法,设置 content_type
使用时 render
:
render file: filename, content_type: "application/rss"
我在一个普通的 Rails 4.2.4 应用程序中测试了这个策略。这就是我定义 Controller 的方式:
class WelcomeController < ApplicationController
def index
render inline: 'Hello World', content_type: 'application/foo; bar=1'
end
end
这是我在点击该操作时在 Chrome 的网络检查器中看到的内容,请注意
Content-Type
在响应标题下:一般
Remote Address:[::1]:3000
Request URL:http://localhost:3000/
Request Method:GET
Status Code:200 OK
响应头
Cache-Control:max-age=0, private, must-revalidate
Connection:Keep-Alive
Content-Length:11
Content-Type:application/foo; bar=1; charset=utf-8
Date:Tue, 29 Sep 2015 02:53:39 GMT
Etag:W/"b10a8db164e0754105b7a99be72e3fe5"
Server:WEBrick/1.3.1 (Ruby/2.2.2/2015-04-13)
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:3825d446-44dc-46fa-8aed-630dc7f001ae
X-Runtime:0.022774
X-Xss-Protection:1; mode=block
关于ruby-on-rails - 在 Rails 4.2 中,如何设置带有媒体类型参数的响应 Content-Type header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32834752/