2013-03-08 138 views
10

我有這個簡單的函數來獲取HTML頁面並將其作爲字符串返回;儘管有時我得到了404。如何才能返回HTML字符串只有當請求成功,並返回類似BadRequest時,它是404或任何其他錯誤狀態代碼?Web響應狀態代碼

public static string GetPageHTML(string link) 
{ 
    using (WebClient client= new WebClient()) 
    { 
     return client.DownloadString(link); 
    } 
} 
+2

抓住'WebException'看看什麼是回報.. – 2013-03-08 08:15:49

回答

23

你可以趕上引發WebException:

public static string GetPageHTML(string link) 
{ 
    try 
    { 
     using (WebClient client = new WebClient()) 
     { 
      return client.DownloadString(link); 
     } 
    } 
    catch (WebException ex) 
    { 
     var statusCode = ((HttpWebResponse)ex.Response).StatusCode; 
     return "An error occurred, status code: " + statusCode; 
    } 
} 

當然,這將是更合適的捕獲這個異常調用代碼,甚至沒有試圖解析HTML,而不是把try/catch語句在函數本身。