WebRequest.GetResponse 不会返回 404 错误

本文关键字:错误 返回 GetResponse WebRequest | 更新日期: 2023-09-27 18:36:02

我们遇到了一个奇怪的问题。直到昨天和多年来,我们一直在应用程序中使用一小段代码来访问特定的URL,以检查其中是否存在特定文件:

    public static bool IsUpdateAvailable ()
    {
        System.Net.WebRequest webRequest = System.Net.WebRequest.Create("http://site/updatefile.exe");
        System.Net.WebResponse webResponse;
        try
        {
            webResponse = webRequest.GetResponse();
        }
        catch (System.Net.WebException e) //If WebException exception thrown then couldn't get response from address
        {
            Console.WriteLine("This program is throw a WebException."+
                        "'n'nException Message :" + e.Message);
              if(e.Status == System.Net.WebExceptionStatus.ProtocolError) return false;
        }
        catch (Exception e) //If general exception thrown then couldn't get response from address
        {
            return false;
        }
        return true;
    }

从昨天开始,如果检查的文件或 URL 不存在,上面的代码就会停止返回 404 错误,因此始终返回 true。我们无法从 c# 角度解释会发生什么。任何帮助将不胜感激。

WebRequest.GetResponse 不会返回 404 错误

抓住WebException,从中你可以恢复WebResponse Response,将其投射到HttpWebResponse。在那里,您将获得所需的状态代码。