如何在 scala play 2.6 中的 ActionBuilder 中设置会话?

How to set a session in ActionBuilder in scala play 2.6?

documentation on ActionBuilder 包含三个节点的管道:身份验证、添加信息、验证步骤。

我想在身份验证步骤设置会话值。我的意思是这里的 .withSession Ok(_).withSession(_)

import play.api.mvc._

class UserRequest[A](val username: Option[String], request: Request[A]) extends WrappedRequest[A](request)

class UserAction @Inject()(val parser: BodyParsers.Default)(implicit val executionContext: ExecutionContext)
    extends ActionBuilder[UserRequest, AnyContent] with ActionTransformer[Request, UserRequest] {
    def transform[A](request: Request[A]) = Future.successful {
        new UserRequest(request.session.get("username"), request)
    }
}

您需要执行操作组合以向请求会话添加值,如下所示:

object WithSession extends ActionBuilder[Request] {
  def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
      block(request).map(_.withSession("key" -> "value"))
  }
}

在你的控制器中:

def index = WithSession {
  Ok("result")
}