【问题标题】:System.Net.WebException on Console Application控制台应用程序上的 System.Net.WebException
【发布时间】:2012-02-04 07:20:56
【问题描述】:

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

system.net.webexception 操作超时 system.net.httpwebrequest.getresponse

我将超时设置为 15000 毫秒,即 15 秒。我在请求时查看了萤火虫,它说请求已中止,我没有看到状态码。但我想知道为什么我设置超时时会得到这个期望?

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

【问题讨论】:

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


    【解决方案1】:

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

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

    (MSDN)

    【讨论】:

    • 所以如果状态不是正常返回,我需要像处理这个异常一样处理这个异常吗?
    • 是的,异常本质上是说服务器没有在给定的限制内响应。它没有响应的原因可能会有所不同。您可以尝试从抛出的异常中获取 http 代码。看到这个答案:stackoverflow.com/questions/3614034/…
    猜你喜欢
    • 2010-11-04
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    相关资源
    最近更新 更多