1

我想 play.api.mvc.Action在游戏中定制一个:

  1. 将解析并返回请求中的一些自定义数据(例如访问令牌或协议缓冲区)
  2. 可以与其他动作链接

例如:

def something = DecodeAccessToken { token: AccessToken => 
  Action {
    // do something with token
    Ok
  }
}

如果令牌不存在,则DecodeAccessToken操作应使用Unauthorized或提前返回BadRequest

4

2 回答 2

1

这不是Play 中推荐的方法!文档,但我会这样写:

def DecodeAccessToken(body: AccessToken => Result)(implicit request: Request[_]): Result = {
  val token: AccessToken = // deserialize token from request
  body(token)
}

def something = Action { implicit request =>
  DecodeAccessToken { token: AccessToken =>
    Ok
  }
}
于 2012-08-25T04:38:52.943 回答
0

您可以按如下方式使用基本模板:

trait DecodeAccessToken[A] extends Action[A]
object DecodeAccessToken {
  def apply[A](bodyParser: BodyParser[A])(block: AccessToken=>Request[A] => Result) = new DecodeAccessToken[A] {
    def parser = bodyParser
    def apply(req: Request[A]) = {
      val token: AccessToken = //deserialize token from request

      // If there is a problem with the token, do not call `block` below
      // Instead just return Results.BadRequest

      block(token)(req)
    }
  }
  def apply(block: AccessToken => Request[AnyContent] => Result): Action[AnyContent] = {
    DecodeAccessToken(BodyParsers.parse.anyContent)(block)
  }
}
于 2012-08-24T05:34:54.240 回答