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

删除回忆录丶 提交于 2019-12-05 10:10:12

Web servers often return an error page with more details (either HTML or plain text depending on the server). You can grab this by catching WebException and reading the response stream from its Response property.

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 />");
        }

Try catching a HttpException and call GetHtmlErrorMessage() on it

I've always liked

Debug.WriteLine( ex.ToString() );

You should use HttpWebRequest and HttpWebResponse. WebClient is the simplest thing to use to do basic web communication, but it does not provide the functionality you need. I think it's better to do this because it will not throw an exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!