当服务器响应system.net.webeexception 422时,如何检索从远程服务器传回的内容

本文关键字:服务器 检索 webeexception net system 响应 422时 何检索 | 更新日期: 2023-09-27 18:10:09

我正在使用一个api,该api还返回一个有效的xml字符串,其中包含在他们的系统上遇到的错误。

<?xml version="1.0" encoding="UTF-8"?>
<error>
   <request>Request made to server</request>
   <message>No user found for account 12345</message>
</error>

是否有任何方法从远程服务器获得该xml System.Net.WebException对象?提前感谢:)

当服务器响应system.net.webeexception 422时,如何检索从远程服务器传回的内容

直接来自MSDN文档:

当WebRequest类的子类抛出webeexception时,的Internet响应应用程序。

所以如果你如果你在读取响应时得到异常,你应该能够读取response属性来获取XML内容

当然可以!只需要在request.GetResponse()周围抛出一个try-catch,捕获一个webeexception并从exceptions Response属性中读取。

WebRequest request = WebRequest.Create("http://www.google.com/ohnoa404");
WebResponse response;
try
{
    response = request.GetResponse();
}
catch (WebException ex)
{
    response = ex.Response;
}
String responseString = String.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    responseString = reader.ReadToEnd();
}