本文介绍了到目前为止,RequestHeader在Play Framework 2.0中均不包含请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果在文档:

trait RequestHeader extends AnyRef
The HTTP request header. Note that it doesn’t contain the request body yet.

从2.0版本开始似乎..

That seems from very 2.0 version ..

尝试获取异步处理请求正文的示例.为了将其记录到文件中.

Trying to get example of async handing the request's body. In order to log it to file.

object AccessLoggingFilter extends EssentialFilter {

      def apply(inputAction: EssentialAction) = new EssentialAction { request =>

    val accessLogger = Logger("access")

    def apply(requestHeader: RequestHeader): Iteratee[Array[Byte], Result] = { ...

  Logger.info(s"""Request:
            Body             = ${requestHeader.???} """)

在SO上有一些哲学上的答案,在这里例如.但是我不会称它为答案.

There are some philosophical answers on SO, here for example. But I would not call it answer..

推荐答案

是的,播放不允许在过滤器阶段访问请求的正文.

Yes, play doesn't allow to access the body of the request in the filter stage.

如果只想记录正文,则可以为此创建一个新动作并将其组成.

If you only want to log the body, you can create a new action for that and compose it.

这是播放2.6中的示例

This is an example from play 2.6

def withLogging(action: Action[AnyContent]): Action[AnyContent] = {
    Action.async(action.parser) { request =>
      request.body match {
        case AnyContentAsJson(json) => Logger.info("JSON body was: " + Json.stringify(json))
        case _ => //implement more logging of different body types
      }
      action(request)
    }
  }


  def foo = withLogging(Action.async(cc.parsers.anyContent) { implicit request =>
    // do your stuff
  }))

如果只有json端点,则可以为此编写特定的操作.

If you have only json endpoints, you can write a specific action for that.

这篇关于到目前为止,RequestHeader在Play Framework 2.0中均不包含请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 14:00