播放2-在所有回应上设置标题? [英] Play 2 - Set header on all responses?
问题描述
我从了解如何在Play 2.0中设置HTTP标头(scala) )?,您可以根据具体情况通过执行Ok("hello").withHeaders(PRAGMA -> "no-cache")
来设置响应标头.
I'm aware from Setting HTTP headers in Play 2.0 (scala)? that you can set response headers on a case-by-case basis by doing, for example, Ok("hello").withHeaders(PRAGMA -> "no-cache")
.
如果要在所有操作的响应上设置该标头或几个其他标头,该怎么办?您不想在任何地方重复withHeaders
.而且由于这更像是应用程序范围的配置,因此您可能不希望Action编写者必须使用其他语法来获取标头(例如OkWithHeaders(...)
)
What if you want to set that header, or a few different headers, on responses from all your Actions? You wouldn't want to repeat the withHeaders
everywhere. And since this is more like an application-wide configuration, you might not want Action writers to have to use a different syntax to get your headers (e.g. OkWithHeaders(...)
)
我现在拥有的是一个基本的Controller类,看起来像
What I have now is a base Controller class that looks like
class ContextController extends Controller {
...
def Ok(h: Html) = Results.Ok(h).withHeaders(PRAGMA -> "no-cache")
}
但是感觉不太正确.感觉应该有更多的AOP风格的方式来定义默认标头,并将其添加到每个响应中.
but that doesn't feel quite right. It feels like there should be more of an AOP-style way of defining the default headers and having them added to each response.
推荐答案
在您的Global.scala
中,将每个调用包装在一个动作中:
In your Global.scala
, wrap every call in an action:
import play.api._
import play.api.mvc._
import play.api.Play.current
import play.api.http.HeaderNames._
object Global extends GlobalSettings {
def NoCache[A](action: Action[A]): Action[A] = Action(action.parser) { request =>
action(request) match {
case s: SimpleResult[_] => s.withHeaders(PRAGMA -> "no-cache")
case result => result
}
}
override def onRouteRequest(request: RequestHeader): Option[Handler] = {
if (Play.isDev) {
super.onRouteRequest(request).map {
case action: Action[_] => NoCache(action)
case other => other
}
} else {
super.onRouteRequest(request)
}
}
}
在这种情况下,我只在dev模式下调用该动作,这对于无缓存指令最有意义.
In this case, I only call the action in dev mode, which makes most sense for a no-cache instruction.
这篇关于播放2-在所有回应上设置标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!