2011-01-05 66 views
1

是否有人知道任何好的鏈接驗證API。我不想尋找任何類型的網絡爬蟲,只是爲了驗證整個頁面或單個鏈接。我一直在尋找一個,因爲我遇到了一些目前無法解決的地雷問題。.NET鏈接驗證器API?

幾個主要問題是:

  • 一些異步Web請求上房
  • 獲得太多的誤判
  • 獲得404當它是一個重定向

我會在案件中張貼我的代碼。

第一種方法是開始驗證

private void urlCheck(Link strUri) 
{ 
    try 
    { 
     Uri uri = new Uri(strUri.URL , 
      (strUri.URL.StartsWith("/")) ? 
       UriKind.Relative : UriKind.Absolute); 

     if(!uri.IsAbsoluteUri) 
      uri = new Uri(_page.HttpDomain + uri); 

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
     request.Method = "GET"; 
     request.UserAgent = 
      "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0)"; 
     request.AllowAutoRedirect = true; 
     request.AllowWriteStreamBuffering = true; 
     request.SendChunked = true; 
     request.UnsafeAuthenticatedConnectionSharing = true; 
     request.KeepAlive = false; 
     request.Referer = "http://www.google.ca/"; 
     // default : WebRequest.DefaultWebProxy 
     request.Proxy = null; 
     request.Timeout = 20000; 

     //do not revalidate this 
     WebPageCollection.DoNotRevalidateLinks.Add(strUri); 
     request.BeginGetResponse(new AsyncCallback(getResponseCallback) , 
      request); 
     _webRequest++; 
    } 
    catch(Exception ex) 
    { 
     Console.WriteLine(ex.StackTrace); 
    } 
} 

第二種方法是回調

private void getResponseCallback(IAsyncResult result) 
{ 
    HttpWebRequest request = (HttpWebRequest)result.AsyncState; 
    string strUri = request.Address.ToString(); 

    Link href = new Link(strUri); 
    href.URLKind = urlKind; 
    href.URLType = UrlType.External; 
    href.URLState = UrlState.Valid; 

    try 
    { 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

     if(response.StatusCode == HttpStatusCode.Redirect) 
     { 
      //TODO: Redirects 
      href.URLState = UrlState.Redirect; 
     } 
    } 
    catch(WebException wex) 
    { 
     href.URLState = UrlState.Broken; 
    } 

    _page.Links.Add(href); 
    _webRequestComplete++; 
    request.EndGetResponse(result); 
} 

兩個遞增變量,以確保這兩個數都是平等的,而且在許多情況下,他們不是,我最終會陷入無限循環。

+2

您需要詳細說明您的問題。對於第一個(異步不會返回),這很容易修復,有一個超時,並假設在超時之後,如果它不返回它是無效的。對於誤報,你需要確定什麼是誤報。對於404重定向,我不明白你是怎麼得到的,要麼你得到了301/302的迴應,要麼你沒有。你需要詳細闡述一個好的答案。 – casperOne 2011-01-05 16:07:09

+0

永遠不會返回我的意思是,即使我的webrequest有超時延遲,我的委託方法也永遠不會被觸發。我相信,它至少應該返回一個超時代碼的響應。但不是。我的意思是誤報,或者一個頁面在其重定向或者頁面聲明爲破壞(404)時表明爲破壞,但其實際有效。讓我知道你是否需要更多信息。 – 2011-01-05 16:16:46

回答

0

是否有理由設置SendChunked?這在大多數情況下會爲我提供ProtocolViolationException。更改urlCheck()方法中的catch語句以重新引發錯誤以查看它。

UPDATE

抱歉讓錘擊點,但我覺得你失去的錯誤。這聽起來像你在ASPX頁面(你提到web.config)這樣做,但你在catch中使用Console.Write,所以你從來沒有看到它。

方法是GET或HEAD,並且或者是的ContentLength大於零或SendChunked爲真:According to MSDN,當ProtocolViolationException將被拋出。

+0

我沒有收到任何錯誤在這一點上拋出。我前一段時間寫過,但如果我記得正確的話,我不得不在webconfig中添加一些東西以使其工作。 – 2011-01-05 17:38:09

+0

需要注意的一個重要事實是它是一個多線程應用程序。 – 2011-01-05 18:17:27

+0

我更新了我的帖子。 – 2011-01-05 18:43:35