2012-01-06 3 views
0

Я написал простое консольное приложение для проверки и проверки, если мой сайт это, проверьте ссылку, которая всегда работает. Проблема заключалась в том, что пошел на другой день, и оно не уведомит меня, это была ошибка:System.Net.WebException на консольном приложении

system.net.webexception the operation has timed out at 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("[email protected]")); 
        contactMsg.From = new MailAddress("[email protected]"); 
        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

Ваш сайт не отвечает в течение 15 секунд, поэтому WebException исключение. Timeout предназначен для исключения.

The Timeout property indicates the length of time, in milliseconds, until the request times out and throws a WebException. The Timeout property affects only synchronous requests made with the GetResponse method. To time out asynchronous requests, use the Abort method.

(MSDN)

+0

Поэтому мне нужно обработать это исключение так же, как я, если разве статус возвращается как Ok правильно? – ios85

+0

Да, исключение по сути говорит о том, что сервер не отвечал в пределах данного предела. Причина, по которой он не отвечал, может варьироваться. Вы можете попытаться получить код http из исключения, которое было выбрано. См. Этот ответ: http://stackoverflow.com/questions/3614034/system-net-webexception-http-codes – keyboardP

Смежные вопросы