我尝试使用PHP使用.net WebAPI。没有错误时,一切正常。但是,当WebApi中出现一些错误时(比如说POST数据的验证失败),我可以轻松获得响应标头,但是我无法找到如何获取响应内容,因此我可以读取引起该错误的原因。
有人知道如何获得它还是不可能?
WebAPI的testController上有test()动作,该动作需要id和text作为请求的内容,否则它将返回HTTP / 1.1 400 Bad Request并告知内容原因。
我使用提琴手来测试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获得了响应头数据,但是我找不到任何方法来获取我在Fiddler中看到的响应内容。
有人知道如何获得它还是不可能?
最后一个提示cURL不是正确答案; P
编辑:在这种情况下,当($ response === false)时,也许值得一提$ 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',
)
因此,最后发布在此处的所有内容均应正常运行。在来到这里之前,我应该做一个孤立的测试用例。(但是在调试之后,您似乎已经尝试了所有选项:P)
因此,我认为'ignore_errors'=> true,该行被某种方式覆盖或忽略了,但是将其与其他假定起作用的代码隔离开来,并且将$ response的值与错误消息的内容隔离开来。
因此,在这种情况下,您需要使用其他不同于if($ response === false)的方式进行错误检查。非常简单的方法可能是if($ http_response_header [0]!='HTTP / 1.1 200 OK'){处理错误!}
感谢大家的投入!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句