WebException如何获得整体响应?


108

在WebException中,我看不到GetResponse的主体。这是我在C#中的代码:

try {                
  return GetResponse(url + "." + ext.ToString(), method, headers, bodyParams);
} catch (WebException ex) {
    switch (ex.Status) {
      case WebExceptionStatus.ConnectFailure:
         throw new ConnectionException();                        
     case WebExceptionStatus.Timeout:
         throw new RequestTimeRanOutException();                     
     case WebExceptionStatus.NameResolutionFailure:
         throw new ConnectionException();                        
     case WebExceptionStatus.ProtocolError:
          if (ex.Message == "The remote server returned an error: (401) unauthorized.") {
              throw new CredentialsOrPortalException();
          }
          throw new ProtocolErrorExecption();                    
     default:
          throw;
    }

我看到标题,但看不到正文。这是来自Wireshark的请求输出:

POST /api/1.0/authentication.json HTTP/1.1    
Content-Type: application/x-www-form-urlencoded    
Accept: application/json    
Host: nbm21tm1.teamlab.com    
Content-Length: 49    
Connection: Keep-Alive    

userName=XXX&password=YYYHTTP/1.1 500 Server error    
Cache-Control: private, max-age=0    
Content-Length: 106    
Content-Type: application/json; charset=UTF-8    
Server: Microsoft-IIS/7.5    
X-AspNet-Version: 2.0.50727    
X-Powered-By: ASP.NET    
X-Powered-By: ARR/2.5

Date: Mon, 06 Aug 2012 12:49:41 GMT    
Connection: close    

{"count":0,"startIndex":0,"status":1,"statusCode":500,"error":{"message":"Invalid username or password."}}

是否可以通过某种方式在WebException中查看消息文本?谢谢。


您是否尝试过(HttpWebResponse)we.Response; 您捕获的WebException在哪里“我们”?
贾斯汀·哈维

2
要在重新引发的异常中保留堆栈跟踪,请不要使用,throw ex;而是简单地使用throw;(在默认情况下)。另外(如果需要),我会将原始WebException放入自定义Exceptions的InnerException中(通过适当的构造函数)。
user1713059 2014年

Answers:


201
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();

dynamic obj = JsonConvert.DeserializeObject(resp);
var messageFromServer = obj.error.message;

8
对于任何不熟悉JsonConvert的人,都需要从nuget软件包管理器中获取Newtonsoft.Json。
凯尔(Kyle)

由于Newtonsoft.Json是可选的,请用凯尔的解释更新答案。
Jeroen

3
另外,请说明此代码应放在请求应进入的Try-Catch代码块的Catch fallback子句中。我知道这种情况对于关注读者和@iwtu来说是显而易见的,但是全面的答案可以对阅读此答案的初学者产生真正的影响;)
Jeroen

2
StreamReader实现IDisposable,因此将其包装在using语句中不是最佳实践吗?快速浏览StreamReader的Dispose方法表明它在那里进行了一些重要的清理。
sammy34

@ sammy34不用担心,因为这里没有非托管代码/数据在这种情况下,垃圾集气器可以很容易地处理它......(但是,使用使用是一个好习惯总是)
LB

41
try {
 WebClient client = new WebClient();
 client.Encoding = Encoding.UTF8;
 string content = client.DownloadString("https://sandiegodata.atlassian.net/wiki/pages/doaddcomment.action?pageId=524365");
 Console.WriteLine(content);
 Console.ReadKey();
} catch (WebException ex) {
 var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
 Console.WriteLine(resp);
 Console.ReadKey();
}

4

这只会改善现有答案。我编写了一种方法,用于处理带有增强消息的投掷/重新投掷的细节,其中包括响应正文:

这是我的代码(在Client.cs中):

/// <summary>
///     Tries to rethrow the WebException with the data from the body included, if possible. 
///     Otherwise just rethrows the original message.
/// </summary>
/// <param name="wex">The web exception.</param>
/// <exception cref="WebException"></exception>
/// <remarks>
///     By default, on protocol errors, the body is not included in web exceptions. 
///     This solutions includes potentially relevant information for resolving the
///     issue.
/// </remarks>
private void ThrowWithBody(WebException wex) {
    if (wex.Status == WebExceptionStatus.ProtocolError) {
        string responseBody;
        try {
            //Get the message body for rethrow with body included
            responseBody = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();

        } catch (Exception) {
            //In case of failure to get the body just rethrow the original web exception.
            throw wex;
        }

        //include the body in the message
        throw new WebException(wex.Message + $" Response body: '{responseBody}'", wex, wex.Status, wex.Response);
    }

    //In case of non-protocol errors no body is available anyway, so just rethrow the original web exception.
    throw wex;
}

您可以在catch子句中使用它,就像OP所示:

//Execute Request, catch the exception to eventually get the body
try {
    //GetResponse....
    }
} catch (WebException wex) {
    if (wex.Status == WebExceptionStatus.ProtocolError) {
        ThrowWithBody(wex);
    }

    //otherwise rethrow anyway
    throw;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.