尝试从2.5.x迁移到2.6.x.我有特质安全与旧方法IsAuthenticatedAsync,我正在尝试编写新方法IsAuthenticatedAsyncNew。编译器说Action.async已被弃用,所以我试图用ActionBuilder替换Action.asyinc块,但我很难,因为我找不到好的2.6.x示例如何做到这一点。
trait Secured {
private def username(request: RequestHeader) = request.session.get("username")
private def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.login())
def userService: UserService
def cc: ControllerComponents
/**
* Async action for authenticated users.
*/
def IsAuthenticatedAsync(f: => User => Request[AnyContent] => Future[Result]) = Security.Authenticated(username, onUnauthorized) { user =>
Action.async{ implicit request =>
val _user = userService.findByUsername(user)
if(_user.nonEmpty)
f(_user.get)(request)
else
Future.successful(Results.Redirect(routes.Application.login()))
}
}
def IsAuthenticatedAsyncNew(f: => User => Request[AnyContent] => Future[Result]) = new ActionBuilder[Request, AnyContent] {
override def invokeBlock[A](request: Request[A], block: Request[A] => Future[Result]) = {
val username = request.session.get("username")
val user = userService.findByUsername(username.get)
user match {
case Some(user) => f(user)(request)
case None => Future.successful(Results.Redirect(routes.Application.login()))
}
}
override protected def executionContext: ExecutionContext = cc.executionContext
override def parser: BodyParser[AnyContent] = cc.parsers.defaultBodyParser
}
}
编译器返回错误
Error:(40, 36) type mismatch;
found : play.api.mvc.Request[A]
required: play.api.mvc.Request[play.api.mvc.AnyContent]
case Some(user) => f(user)(request)
如果我将方法的足迹改为
override def invokeBlock(request: Request[AnyContent], block: Request[AnyContent] => Future[Result])
然后它没有任何东西......它可以这样做吗?
答案 0 :(得分:2)
Action
在BaseController
特征中定义为
def Action: ActionBuilder[Request, AnyContent] = controllerComponents.actionBuilder
这意味着您只需将Action.async
替换为cc.actionBuilder.async(...)
甚至复制该方法
def Action = cc.actionBuilder
并像以前一样使用Action.async
。