【问题标题】:Receiving AbstractController::DoubleRenderError when using authenticate_or_request_with_http_basic()使用 authenticate_or_request_with_http_basic() 时收到 AbstractController::DoubleRenderError
【发布时间】:2012-01-26 08:50:55
【问题描述】:

当我在块的开头添加对authenticate_or_request_with_http_basic 的调用时,我有一个有效的控制器操作中断。这是无效的操作代码:

def index
  authenticate_or_request_with_http_basic do |username, password|
    username == "test1" and password == "test"
  end

  render layout: false, content_type: 'application/xml'
end

我在浏览器窗口中收到“AbstractController::DoubleRenderError”错误响应,并显示以下消息:

在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。还要注意,redirect和render都不会终止action的执行,所以如果你想在redirect后退出一个action,你需要做一些类似“redirect_to(...) and return”的操作。

当我将“authenticate_or_request_with_http_basic”逻辑放在一个单独的操作中,然后配置一个 before_filter 来为索引操作运行它时,一切都很好。但是,我不会将这个逻辑重用于索引以外的任何操作,我想知道为什么上面的代码不起作用。

解决方案

在 Tyler 和 RKB 的帮助下,我找到了解决方案。这里是:

authenticated = authenticate_or_request_with_http_basic "Authentication Required" do |username, password|
  @user = User.find_by_username(username)
  @user != nil && password == "test"
end
return unless authenticated == true 

authenticate_or_request_with_http_basic 如果身份验证成功,则返回“true”。失败时返回 401。

【问题讨论】:

    标签: ruby-on-rails-3.1 http-authentication actionview actioncontroller


    【解决方案1】:

    这听起来像 authenticate_or_request_with_http_basic 要么呈现要么重定向。我猜当你将它移动到 before_filter 时它会起作用,因为它返回 false 取消回调链并导致第二次渲染不发生?只是猜测...

    【讨论】:

      【解决方案2】:

      authenticate_or_request_with_http_basic 调用 render 以发送执行 HTTP 基本身份验证所需的 HTTP 响应(状态代码 401 未授权)。详情请见Rails code

      【讨论】:

      • 在这种情况下,一旦 authenticate_or_request_with_http_basic 返回 false,我如何停止进一步执行操作?
      • 我会将 authenticate_or_request_with_http_basic 调用放在 before_filter 中。
      • 如何在单个操作中停止进一步执行?
      猜你喜欢
      • 2015-11-27
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多