如何在收到请求后更改请求的mime类型?



我的客户发送我的rails应用程序请求作为XML或HTML。在rails 2.10下,我的控制器动作有一个responds_to块,包含wants.html和wants.xml。我的客户将他们的HTTP标头设置为Content-Type=text/xml和Accept=text/xml(如果他们想要xml的话),并且几乎省略了HTML的标头。伟大的工作。

事实证明,我的许多客户一直省略了Accept=text/xml头,但只要他们设置Content-type=text/xml, respond_to块就会触发wants.xml。在rails3中,respond_to块(正确地)只在Accept=text/xml设置时触发wants.xml。

与其让我的许多客户更改他们的程序,我如何告诉rails3请求需要XML呢?我在想,如果我看到Content-Type设置为text/xml,我也会强制Accept为text/xml。

我尝试更改请求。像这样直接Env哈希:

class MyController < ApplicationController
def my_xml_or_html_action
  if request.env['CONTENT_TYPE'].to_s.match(/xml/i)
    request.env['HTTP_ACCEPT'] = 'text/xml'
  end
  respond_to do |wants|
    wants.html { redirect_to html_response }
    wants.xml { render xml_response }
  end
end

但这不起作用。我可以完全放弃respond_to,像这样做:

class MyController < ApplicationController
def my_xml_or_html_action
  if request.env['CONTENT_TYPE'].to_s.match(/xml/i)
    redirect_to html_response
  else
    render xml_response
  end
end

但这似乎是蛮力。有没有更简单的方法来实现这一点?

尝试:

params[:format] = :xml

最新更新