2012-11-28 38 views
0

直到最近我用HttpWebRequest來確定一個文件是否存在於互聯網上。但是現在,我意識到如果服務器不存在,服務器可以處理404,並且我只會得到默認的404服務器錯誤頁面。在這種情況下,HttpWebRequest 不會引發異常。我想不出一種方法來判斷是否發生了404錯誤。
如何確定服務器上是否存在Internet文件?

任何想法?

回答

2

檢查HttpWebResponse中的StatusCodeStatusResponse。根據收到的價值,您總是可以使用throw

+0

如果我理解正確,是不是拋出'WebException'的'GetResponse'方法?在這種情況下,答覆尚未收到。 – spender

+0

你能舉個例子嗎?我嘗試使用你的想法,但我無法解決我的問題....你是否將返回的WebResponse轉換爲HttpWebResponse? -----(HttpWebResponse)await request.GetResponseAsync(); – Keeper

0

在返回'未找到頁面'頁面的服務器上,如果您嘗試在瀏覽器中獲取不具有遠程的文件並查看開發工具,則返回碼仍爲404 Not Found。

通常,您會希望HttpWebRequest.GetResponse方法返回http響應代碼,而不是.NET throws an exception用於http錯誤。

try { 
    HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com"); 
    using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse()) 
    {    
     if (httpRes.StatusCode == HttpStatusCode.OK) 
      Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}", httpRes.StatusDescription); 
     // Releases the resources of the response. 
     httpRes.Close(); 
    } 
} 
catch (WebException ex) { 
    Console.WriteLine("Error returned: {0}",ex.Response); 
    // can throw again here. 
    throw; 
} 
+0

嗯......這是一個好主意。對不起,我的無知,但我如何訪問返回代碼? – Keeper

0

如果GetResponse或其等價異步是拋出,趕上WebException,你會發現它有許多方便的性能。

特別是,WebException.Response可能對您非常有用。

相關問題