【问题标题】:500 Internal Server Error when using HttpWebRequest, how can I get to the real error?使用 HttpWebRequest 时出现 500 内部服务器错误,我怎样才能找到真正的错误?
【发布时间】:2026-02-19 04:25:02
【问题描述】:

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

这是代码:

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) 内部服务器错误”。我在调试中查看了异常,但我需要的信息不存在 - 我想需要读入响应才能看到该信息,但它永远不会那么远。

如果我接受请求并将其直接粘贴到我的浏览器中,我可以看到从我正在调用的 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),但我看不到我需要的信息,只有一个 Header 信息的负载。

【问题讨论】:

    标签: http


    【解决方案1】:

    你可以从异常中得到错误响应......

    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
          }
       }
    }
    

    【讨论】:

    • 现在看看这个。这段代码遇到的第一个问题是“ResponseError”似乎不是 WebExceptionStatus 枚举 msdn.microsoft.com/en-us/library/… 的一部分
    • 尽管如此,仍将其标记为正确,因为此答案确实帮助我找到了解决方案。我的代码(vb.net)看起来像: Catch ex As WebException Using reader As StreamReader = New StreamReader(ex.Response.GetResponseStream()) strXML = reader.ReadToEnd() End Using
    • 对不起,它实际上应该是 WebExceptionStatus.ProtocolError。在这种情况下,响应对象应该有错误流。现在,尽管如此,如果您的错误流为空,则可能意味着服务器没有发送任何内容,或者某处存在错误。您可以使用 ferozedaud.blogspot.com/2009/08/tracing-with-systemnet.html 获取跟踪日志吗?这将显示服务器是否发送了响应实体。
    【解决方案2】:
            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)
            {
            }
    

    就这么简单,你会在字符串错误中得到完整的响应。

    【讨论】:

    • +1 捕获实际的 WebException 比捕获通用的异常要好,否则你基本上会忽略所有其他异常。
    【解决方案3】:

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

    【讨论】:

    • @DannykPowell:这是 Web 开发人员必备的。
    • 或者只是 chrome 开发者工具 :) 网络选项卡也一样,它有更少的选项来干扰消息,但它的干净和适当的过滤已经准备好:)
    最近更新 更多