1

當我在塊的開頭添加對authenticate_or_request_with_http_basic的調用時,我有一個工作控制器動作。這裏是不起作用的動作代碼:使用authenticate_or_request_with_http_basic()時接收AbstractController :: DoubleRenderError()

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_to(...)並返回」之類的操作。

當我將「authenticate_or_request_with_http_basic」邏輯放在一個單獨的動作中,然後配置一個before_filter來爲索引動作運行它時,一切都很好。然而,我並沒有重複使用這個邏輯來進行索引以外的其他操作,我想知道爲什麼上面的代碼不起作用。

解決方案

我能找到泰勒和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。

回答

1

聽起來像authenticate_or_request_with_http_basic是呈現或重定向。我猜它會在它移動到before_filter時起作用,因爲它會返回false,從而取消回調鏈並導致第二次渲染不會發生?只是猜測...

1

authenticate_or_request_with_http_basic調用呈現發送HTTP基本身份驗證所需的HTTP響應(狀態碼401未經授權)。詳細信息請參見Rails code

+0

在這種情況下,一旦authenticate_or_request_with_http_basic返回false,我該如何暫停動作的進一步執行? – 2011-12-22 22:52:00

+0

我會將authenticate_or_request_with_http_basic調用放在before_filter中。 – rkb 2011-12-23 00:28:53

+0

在單個動作中如何進一步執行? – 2011-12-23 02:44:25

相關問題