代码之家  ›  专栏  ›  技术社区  ›  DannykPowell

500内部服务器错误使用httpwebrequest时,如何才能得到真正的错误?

  •  7
  • DannykPowell  · 技术社区  · 15 年前

    我正在尝试改进提供的信息,以响应应用程序中处理的错误。

    这是代码:

    Try
            httpRequestObj = HttpWebRequest.Create(strRequest)
            httpRequestObj.Method = "GET"
            httpRequestObj.UseDefaultCredentials = True
    *       httpResponse = httpRequestObj.GetResponse
            Using reader As StreamReader = New StreamReader(httpResponse.GetResponseStream())
                strXML = reader.ReadToEnd()
            End Using
        Catch ex As WebException
            'do something with ex
        End Try
    

    在*行上引发WebException

    目前,我在异常中看到的只是“远程服务器返回了一个错误:(500)内部服务器错误”。我在debug中查看过这个异常,但是我需要的信息不在那里——我想需要读取响应来查看那个信息,但是它从来没有达到那个程度。

    如果我接受请求并将其直接粘贴到浏览器中,我可以看到从我调用的API返回的XML格式的错误详细信息,信息如下:

    <Error>
      <description>info I want to get to here</description> 
      <detail /> 
      <code>info I want to get to here</code> 
      <source /> 
      <category>info I want to get to here</category> 
      <file>info I want to get to here</file> 
      <line>info I want to get to here</line> 
      <pad /> 
    </Error>
    

    是否有任何方法可以更改此代码,以便通过500个错误并查看实际响应,我希望能够分析此XML以找出失败的真正问题。

    注意:异常确实有一个Ex.Response(system.net.httpwebResponse),但我在其中看不到我需要的信息,只看到一堆头信息。

    3 回复  |  直到 15 年前
        1
  •  17
  •   Community paulsm4    12 年前

    您可以从异常中获得错误响应….

    try
    {
    ....
    } catch(Exception e) {
       if (e is WebException && ((WebException)e).Status==WebExceptionStatus.ProtocolError)
       {
          WebResponse errResp = ((WebException)e).Response;
          using(Stream respStream = errResp.GetResponseStream())
          {
             // read the error response
          }
       }
    }
    
        2
  •  3
  •   RkHirpara    8 年前
            System.Net.WebResponse response = null;
            try
            {
                response = wreq.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    string error = new System.IO.StreamReader(e.Response.GetResponseStream()).ReadToEnd();
                }
            }
            catch (Exception e)
            {
            }
    

    简单地说,您将在字符串错误中得到完整的响应。

        3
  •  2
  •   Ivan Nevostruev    15 年前

    尝试使用 Fiddler . 它正在调试代理,它将显示客户端和服务器之间发送的所有数据。您还可以看到所有的标题和上下文。