我尝试使用.net WebAPI和PHP。没有错误时一切正常。但是,当WebApi出现错误(比如验证POST数据失败)时,我很容易得到响应头,但我无法找到如何获取响应内容,以便我可以读取导致错误的原因。如何获取php file_get_contents()错误响应内容
是否有人有想法如何得到它或者是不可能的?
WebAPI的testController上有test()动作,它需要id和text作为请求的内容,否则它会返回HTTP/1.1 400 Bad Request,并告知原因。
我使用Fiddler来测试的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" : '',}
的回应是:
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}}
所以它告诉在内容 “文本字段是必需的。”用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
{
...
}
所以我从$ http_response_header得到响应报头数据,但我没有找到任何方式得到的回应内容我看到提琴手。
是否有人有想法如何得到它或者是不可能的?
最后一个尖卷曲是不正确的答案,P
编辑:也许这是值得一提的是在$ http_response_header在这种情况下,当($响应===假):
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',
)
http://php.net/stream_get_meta_data –
你已经添加到流选项的'ignore_errors'选项应该照顾这个。你没有运行一个非常老的PHP版本吗?如在5.2.10之前? – iainn
我在php 5.5上运行(对不起,答案花了很长时间,我想回来后,但我忘了) –