ruby-on-rails – 在Rails 4.2中,如何设置具有媒体类型参数的响应内容类型标头?

在早期版本中,这可以工作:
ActionController::Renderers.add(:foo) do | data,options |
  self.content_type = 'application/foo; bar=1'
end

在4.2.4中,这会导致Content-Type标头为空.但是,以下工作,即将Content-Type标头设置为分配给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;巴= 1).

解决方法

首先看一下文档(第2.2.13.1节):

http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

他们给出的示例使用您的替代方法,在使用render时设置content_type:

render file: filename,content_type: "application/RSS"

我在vanilla Rails 4.2.4应用程序中测试了这个策略.这是我定义控制器的方式:

class WelcomeController < ApplicationController
  def index
    render inline: 'Hello World',content_type: 'application/foo; bar=1'
  end
end

这是我在Chrome的网络检查器中看到的,当我点击该操作时,请注意响应标题下的内容类型:

一般

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...