控制台应用程序上的System.Net.WebException

时间:2012-01-06 15:11:18

标签: c# asp.net system.net.webexception

我写了一个简单的控制台应用程序,通过查看始终有效的链接来检查并查看我的网站是否正常运行。问题是它在前几天停了下来并没有通知我,它有错误:

  

system.net.webexception操作已经超时了   system.net.httpwebrequest.getresponse

我将超时设置为15000毫秒,所以15秒。我在查询firebug并查看请求已中止时,我没有看到状态代码。但是我想知道为什么我在设置超时时会得到这个期望?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            WebRequest request = WebRequest.Create("http://MYSITE.com/A/P/LIB/22?encoding=UTF-8&b=100");
            request.Timeout = 15000;
            SmtpClient mailserver = null;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response == null || response.StatusCode != HttpStatusCode.OK)
                {
                    MailMessage contactMsg = new MailMessage();
                    contactMsg.To.Add(new MailAddress("abc123@mysite.com"));
                    contactMsg.From = new MailAddress("donotreply@mysite.com");
                    contactMsg.Subject = "Site is not responding!";
                    contactMsg.IsBodyHtml = true;
                    contactMsg.Body = "<html><body><h1>The Site is not responding</h1> " +
                        "Please check the server. <br /><br />Thank You</body></html>";
                    mailserver = new SmtpClient("smtp.mysite.com", 25);
                    //Setup email message
                    try
                    {
                        mailserver.Send(contactMsg);
                        mailserver.Dispose();
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine(exc.ToString());
                        mailserver.Dispose();
                    }
                    Console.WriteLine("Site is Down!");
                }
                else
                {
                    Console.WriteLine("Site is Up!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                mailserver.Dispose();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的网站在15秒内没有响应,因此会引发WebException异常。 Timeout旨在抛出异常。

  

Timeout属性表示时间长度,以毫秒为单位,   直到请求超时并抛出WebException。超时   property仅影响使用GetResponse进行的同步请求   方法。要使异步请求超时,请使用Abort方法。

MSDN