2012-11-28 34 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可能对您非常有用。

相关问题