获取有关从c#到网站创建httpwebrequest的详细错误信息

时间:2017-03-13 07:59:52

标签: c# httpwebrequest system.net.webexception

我正在使用以下代码检查网站是否有效。如果网站像屏幕截图一样无效。我想记录响应中的详细错误信息。我该怎么做..?请建议.. <code>enter image description here</code>

    private static bool CheckWebSiteActive()
    {
        bool isWebSiteActive = false;
        try
        {
            StreamReader sr = null;
            Stream resst = null;
            HttpWebResponse response = null;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ConfigurationManager.AppSettings["webSiteToCheck"]);
            request.Timeout = 10000;
            request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
            request.Method = "HEAD";

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException we)
            {
                using (WebResponse Wresponse = we.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)Wresponse;
                    Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                    using (Stream data = Wresponse.GetResponseStream())
                    {
                        string text = new StreamReader(data).ReadToEnd();
                        Console.WriteLine(text);
                    }
                }
                //response = (HttpWebResponse)we.Response;
                //resst = response.GetResponseStream();
                //sr = new StreamReader(resst);
                log.Error(sr.ReadToEnd());
            }
            isWebSiteActive = ((int)response.StatusCode == 200 && response.StatusCode == HttpStatusCode.OK) ? true : false;

        }catch(Exception Ex)
        {
            log.Error(Ex.Message.ToString());
        }
        return isWebSiteActive;
    }

先谢谢。

0 个答案:

没有答案