【问题标题】:How can I change the mime type of a request after I receive it?收到请求后如何更改请求的 MIME 类型?
【发布时间】:2011-10-29 15:33:36
【问题描述】:

我的客户以 XML 或 HTML 格式发送我的 rails 应用程序请求。在 Rails 2.10 下,我的控制器操作有一个带有 Wants.html 和 Wants.xml 的 responds_to 块。如果他们想要 XML,我的客户将他们的 HTTP 标头设置为 Content-Type=text/xml 和 Accept=text/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。

我尝试像这样直接更改 request.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

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

【问题讨论】:

    标签: ruby-on-rails-3 mime-types respond-to


    【解决方案1】:

    试试:

    params[:format] = :xml
    

    应该可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 2013-11-08
      • 2010-10-31
      • 2018-03-07
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多