2013-09-25 262 views
0

我已經構建了一個dll,如果我們有Internet,則返回true,否則返回false。 我們做到以下幾點:1。 平呼籲我們的服務器,如果失敗,再嘗試下 2.調用get HTTP請求到我們的WCF API之一,http://db.OurDomainName.com/WCFService.svc/GetCurrentTimeUnixFormat檢查Internet連接C#

這勝利的服務來完成。

在個人電腦和一些服務器(Windows服務器2k R2),它一直工作幾天沒有問題,每2分鐘我們醒來並測試連接。

但是,在Azure虛擬機中,它通過了幾次然後失敗,爲什麼?

我們在網絡瀏覽器中試過: http://db.OurDomainName.com/WCFService.svc/GetCurrentTimeUnixFormat 並查看結果,我們點擊每秒刷新2分鐘,並確認它永不失敗。

但是,從我們的WinService做同樣的幾次失敗後,開始得到超時!!!!

我們不知道爲什麼,好像防火牆,但爲什麼刷新時不阻止瀏覽器!

這裏就是我們在做的.Net:

 private static bool IsConnectedToInternetHttpRequest(string url = "http://db.OurDomainName.com/WCFService.svc/GetCurrentTimeUnixFormat") 
     { 

//GET http://db.OurDomainName.com/WCFService.svc/GetCurrentTimeUnixFormat HTTP/1.1 
//Host: db.tako.com 
//Connection: keep-alive 
//Cache-Control: max-age=0 
//Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
//User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36 
//Accept-Encoding: gzip,deflate,sdch 
//Accept-Language: en-US,en;q=0.8 

      try 
      { 
       var request = (HttpWebRequest)WebRequest.Create(url); 
       request.Timeout = (int)new TimeSpan(0, 0, 30).TotalMilliseconds; 
       request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
       request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36"; 
       request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Refresh); 
       request.KeepAlive = true; 

       var response = (HttpWebResponse)request.GetResponse(); 

       if (response.StatusCode == HttpStatusCode.OK) 
       { 
        return true; 
       } 
       else 
       { 
        return false; 
       } 
      } 
      catch (Exception) 
      { 
       return false; 
      } 
     } 

回答

0
[DllImport("wininet.dll", SetLastError = true)] 
static extern bool InternetCheckConnection(string lpszUrl, int dwFlags, int dwReserved); 

const int FLAG_ICC_FORCE_CONNECTION = 1; 
bool internetStatus = false; 

if (InternetCheckConnection("http://www.google.com", FLAG_ICC_FORCE_CONNECTION, 0) || 
    InternetCheckConnection("http://www.microsoft.com", FLAG_ICC_FORCE_CONNECTION, 0) || 
    InternetCheckConnection("http://www.facebook.com", FLAG_ICC_FORCE_CONNECTION, 0)) 
{ 
    internetStatus = true; 
} 
1
public Contructor(){ 
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += new System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged); 
} 

private void NetworkChange_NetworkAvailabilityChanged(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e) 
     { 

       if (e.IsAvailable) 
       { 
        //connected 
       } 
       else 
       { 
        //disconnected 
       } 

     }