How to Get Raw Request Body in Magento 2 Controller

controllersmagento2

I've been battling this issue for a bit now and it's driving me crazy.

Essentially I'm trying to get the raw posted data sent to my controller (which extends \Magento\Framework\App\Action\Action).

In Magento 1.x you can fetch the raw request body in a controller by running the following in a controller method:

$data = $this->getRequest()->getRawBody();

Now that I'm trying to port a M1 module to M2 I've been unable to figure out the correct way to do this.

I've tried the following (and poked at a few other things to no avail):

$rawBody = $this->_rawBody;
$postValueData = $this->_request->getPostValue();
$postData = $this->_request->getPost();
$getData = $this->_request->getParams();

$this->logger->debug('$rawBody:');
$this->logger->debug(print_r($rawBody, true));
$this->logger->debug('$postValueData:');
$this->logger->debug(print_r($postValueData, true));
$this->logger->debug('$postData:');
$this->logger->debug(print_r($postData, true));
$this->logger->debug('$getData:');
$this->logger->debug(print_r($getData, true));

The output I get in my log file from this is the following:

[2018-06-15 07:09:03] main.DEBUG: $rawBody: [] []
[2018-06-15 07:09:03] main.DEBUG:  [] []
[2018-06-15 07:09:03] main.DEBUG: $postValueData: [] []
[2018-06-15 07:09:03] main.DEBUG: Array
(
)
 [] []
[2018-06-15 07:09:03] main.DEBUG: $postData: [] []
[2018-06-15 07:09:03] main.DEBUG: Zend\Stdlib\Parameters Object
(
    [storage:ArrayObject:private] => Array
        (
        )

)
 [] []
[2018-06-15 07:09:03] main.DEBUG: $getData: [] []
[2018-06-15 07:09:03] main.DEBUG: Array
(
)
 [] []

As you can see, not a lot of data there.

The way I'm testing this is by running the following from the command line:

curl -H "Content-Type: application/json" -X POST --data '{"orderReference": 000000001}' http://127.0.0.1:8080/my/controller/

I feel like I'm missing something obvious here…

Best Answer

if you want to get Body, please use the below function

$this->getRequest()->getContent()
Related Topic