什么时候 request.attrs.get 在 Scala Play 自定义过滤器中 return None?

When would request.attrs.get in a Scala Play custom filter return None?

中,建议使用如下代码:

// in your filter
val handlerDef: Option[HandlerDef] = request.attrs.get(Router.Attrs.HandlerDef)

我不确定这里发生了什么 - .get 在此 val 上安全吗(将其从 Option 中删除)?在什么情况下此代码会导致 None(即 Router.Attrs.HandlerDef 何时不存在)?

我正在使用 Scala 和 PlayFramework 2.6。

根据Route modifier tags

Please be aware that the HandlerDef request attribute exists only when using a router generated by Play from a routes file. This attribute is not added when the routes are defined in code, for example using the Scala SIRD or Java RoutingDsl. In this case request.attrs.get(HandlerDef) will return None in Scala or null in Java. Keep this in mind when creating filters.

因此,如果您正在使用 routes 文件,那么 Router.Attrs.HandlerDef 应该始终可用。作为 shorthand 而不是

val handlerDef: HandlerDef = request.attrs.get(Router.Attrs.HandlerDef).get

你可以像这样使用 apply

val handlerDef: HandlerDef = request.attrs(Router.Attrs.HandlerDef)