简体   繁体   English

如何使用.NET读取ASP.NET内部服务器错误描述?

[英]How to read an ASP.NET internal server error description with .NET?

Behold the code: 看看代码:

using (var client = new WebClient())
{
    try
    {
        var bytesReceived = client.UploadData("http://localhost", bytesToPost);
        var response = client.Encoding.GetString(bytesReceived);
    }
    catch (Exception ex)
    {
    }
}

I am getting this HTTP 500 internal server error when the UploadData method is called. 调用UploadData方法时,我收到此HTTP 500内部服务器错误。 But I can't see the error description anywhere in the "ex" object while debugging. 但是在调试时我无法在“ex”对象中的任何位置看到错误描述。 How do I rewrite this code so I can read the error description? 如何重写此代码以便我可以阅读错误说明?

Web servers often return an error page with more details (either HTML or plain text depending on the server). Web服务器通常返回包含更多详细信息的错误页面(HTML或纯文本,具体取决于服务器)。 You can grab this by catching WebException and reading the response stream from its Response property. 您可以通过捕获WebException并从其Response属性中读取响应流来获取此信息。

I found useful information for debugging this way: 我找到了有用的调试信息:

        catch (WebException ex)
        {
            HttpWebResponse httpWebResponse = (HttpWebResponse)ex.Response;
            String details = "NONE";
            String statusCode = "NONE";
            if (httpWebResponse != null)
            {
                details = httpWebResponse.StatusDescription;
                statusCode = httpWebResponse.StatusCode.ToString();
            }

            Response.Clear();
            Response.Write(ex.Message);
            Response.Write("<BR />");
            Response.Write(ex.Status);
            Response.Write("<BR />");
            Response.Write(statusCode);
            Response.Write("<BR />");
            Response.Write(details);
            Response.Write("<BR />");
            Response.Write(ex);
            Response.Write("<BR />");
        }

尝试捕获HttpException并在其上调用GetHtmlErrorMessage()

我一直很喜欢

Debug.WriteLine( ex.ToString() );

You should use HttpWebRequest and HttpWebResponse. 您应该使用HttpWebRequest和HttpWebResponse。 WebClient is the simplest thing to use to do basic web communication, but it does not provide the functionality you need. WebClient是用于进行基本Web通信的最简单方法,但它不提供您需要的功能。 I think it's better to do this because it will not throw an exception. 我认为这样做更好,因为它不会抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM