我使用以下代码完成外部API调用。
WebResponse response = request.GetResponse();
string JSONResult = null;
var data = response.GetResponseStream();
using (var reader = new StreamReader(data))
{
JSONResult = reader.ReadToEnd();
}
当外部API出现异常时,request.GetResponse会抛出错误。但是,我无法获得显示的消息,例如
{
"Message": "No HTTP resource was found that matches the request URI '<site>/Foo'.",
"MessageDetail": "No type was found that matches the controller named 'Foo'."
}
虽然这是在Fiddler和Postman中显示的,但是当它作为例外被抛出时,我无法在任何地方收到此消息。
如果在外部API调用时发生错误,如何获取此特定详细信息?
答案 0 :(得分:2)
您需要捕获异常,然后阅读异常的响应流。读取异常的响应流与读取请求的响应相同。方法如下:
WebRequest request =
WebRequest.Create("http://...");
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (WebException webEx)
{
if (webEx.Response != null)
{
using (var errorResponse = (HttpWebResponse)webEx.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
// TODO: use JSON.net to parse this string
}
}
}
}
不要将所有代码放在上面的try块中,因为你只是尝试(ing)和 catch (ing)request.GetResponse()
。其余的代码需要跳出try try块,这样你就可以分别从该代码中捕获异常。