我編寫了一個簡單的控制檯應用程序,通過檢查始終有效的鏈接檢查我的網站是否已啓動。問題是它的另一天去了和它沒有通知我,它有錯誤:控制檯應用程序上的System.Net.WebException
system.net.webexception the operation has timed out at 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("[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();
}
}
}
}
所以我需要爲我所如果狀態心不是返回正確的確定來處理該異常的一樣嗎? – ios85 2012-01-06 16:14:50
是的,這個例外實質上是說服務器在給定的限制內沒有響應。它沒有迴應的原因可能會有所不同。您可以嘗試從拋出的異常中獲取http代碼。看到這個答案:http://stackoverflow.com/questions/3614034/system-net-webexception-http-codes – keyboardP 2012-01-06 16:28:21