I try to consume .net WebAPI with PHP. Everything works fine when there is no error. But when there is some error in WebApi (let say validation of POST data fails) I get the response header easily but I can not find out how to get the response content so I could read what caused the error.
Does some one has idea how to get it or is it impossible?
There is test() action on WebAPI's testController which requires id and text as content of the request or it will return HTTP/1.1 400 Bad Request with content telling the reason.
I use fiddler to test the WebAPI:
POST http://localhost:56018/api/test/test
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:56018
Content-Length: 32
Content: {"id": 5,"text" : '',}
The response is:
HTTP/1.1 400 Bad Request
...
Content-Length: 304
{"args.Text":{"_errors":[{"<Exception>k__BackingField":null,"<ErrorMessage>k__BackingField":"The Text field is required."}],"<Value>k__BackingField":null},"Text":{"_errors":[{"<Exception>k__BackingField":null,"<ErrorMessage>k__BackingField":"The Text field is required."}],"<Value>k__BackingField":null}}
So it's telling in content that "The Text field is required."
Same done with php:
$opts = array('http' =>
[
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query(['id' => 1, 'text' => '']),
'ignore_errors' => true,
]
);
$context = stream_context_create($opts);
$response = file_get_contents('http://localhost:56018/api/test/test', false, $context);
if($response === false)
{
echo json_encode($http_response_header);
die;
}
else
{
...
}
So I get the response header data from $http_response_header, but i don't find any way to get the response content I see with Fiddler.
Does some one has idea how to get it or is it impossible?
And finally one tip cURL is not correct answer ;P
Edit: Maybe it's worth to mention what is in $http_response_header in this case when ($response === false):
array (
0 => 'HTTP/1.1 400 Bad Request',
1 => 'Cache-Control: no-cache',
2 => 'Pragma: no-cache',
3 => 'Content-Type: application/json; charset=utf-8',
4 => 'Expires: -1',
5 => 'Server: Microsoft-IIS/10.0',
6 => 'X-AspNet-Version: 4.0.30319',
7 => 'X-SourceFiles: =?UTF-8?B?QzpcZG90TmV0NDBcR2FsbGUyV2ViQXBpXEdhbGxlMldlYkFwaVxhcGlcZ2FsbGUyXFRlc3Q=?=',
8 => 'X-Powered-By: ASP.NET',
9 => 'Date: Wed, 01 Jun 2016 06:33:11 GMT',
10 => 'Connection: close',
11 => 'Content-Length: 304',
)
ignore_errorsoption that you've added to the stream options should take care of this. You're not running a very old version of PHP are you? As in, older than 5.2.10?