簡體   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