重定向后停止连接

Halt a connection after a redirect

在控制器内部,我正在检查连接的会话以验证会话是否附加到用户。如果没有,我将它重定向到另一个页面。

但是 halt returns 如果我尝试在重定向后调用它,我会出错:

no function clause matching in Plug.Conn.halt/1

如果没有 halt,原始控制器的页面会在控制台中呈现并打印错误(模板在没有用户的情况下呈现):

(exit) an exception was raised: (UndefinedFunctionError) undefined function: nil.username/0

所以我的问题是:是否可以在重定向后调用 halt

这是我的控制器的代码和其中使用的模块。

defmodule Mccm.DashboardController do
  use Mccm.Web, :controller

  import Mccm.Plug.Session
  import Mccm.Session, only: [current_user: 1]

  plug :needs_to_be_logged_in

  def index(conn, _params) do
    conn
    |> render "index.html", user: current_user(conn)
  end
end

defmodule Mccm.Plug.Session do
  import Mccm.Session, only: [logged_in?: 1, is_teacher?: 1]
  import Phoenix.Controller, only: [redirect: 2]
  import Plug.Conn, only: [halt: 1]

  def needs_to_be_logged_in(conn, _) do
    if !logged_in?(conn) do
      conn
      |> redirect to: "/"
      |> halt # this give me an error
    else
      conn
    end
  end
end

这里使用的依赖项:

EDIT 在 Elixir 的 master 分支上,如果函数在没有括号的情况下通过管道传输,如果有参数,编译器将发出警告。


尝试做:

  def needs_to_be_logged_in(conn, _) do
    if !logged_in?(conn) do
      conn
      |> redirect(to: "/") # notice the brackets
      |> halt # this give me an error
    else
      conn
    end
  end

您的代码正在执行:

|> redirect(to: "/", |> halt)

并且错误正确地确定没有以下模式:

halt(to: "/")

有关更详细的说明,请参阅