繁体   English   中英

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

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

看看代码:

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

调用UploadData方法时,我收到此HTTP 500内部服务器错误。 但是在调试时我无法在“ex”对象中的任何位置看到错误描述。 如何重写此代码以便我可以阅读错误说明?

Web服务器通常返回包含更多详细信息的错误页面(HTML或纯文本,具体取决于服务器)。 您可以通过捕获WebException并从其Response属性中读取响应流来获取此信息。

我找到了有用的调试信息:

        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() );

您应该使用HttpWebRequest和HttpWebResponse。 WebClient是用于进行基本Web通信的最简单方法,但它不提供您需要的功能。 我认为这样做更好,因为它不会抛出异常。

暂无
暂无

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

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