C#webrequests-> getresponse强制转换异常,而不返回状态码

问题描述

我正在尝试制作图像抓取工具,现在对于某些页面未指定图像,因此我想根据访问页面时收到的状态码来解析输出,但是当我尝试解析状态码时如果找不到该页面,则会得到一个异常而不是状态代码,知道为什么会发生这种情况吗?

        if (gameinfo != null)
            if (!string.IsNullOrEmpty(gameinfo.image_uri))
                try
                {
                    using (System.Net.WebClient client = new System.Net.WebClient())
                    {
                        // Build Uri and attempt to fetch a response.
                        UriBuilder uribuild = new UriBuilder(gameinfo.image_uri);
                        WebRequest request = WebRequest.Create(uribuild.Uri);
                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                        switch (response.StatusCode)
                        {
                            // Page found and valid entry.
                            case HttpStatusCode.OK:
                                using (Stream stream = client.OpenRead(uribuild.Uri))
                                {
                                    Console.WriteLine(String.Format("Downloading {0}",uribuild.Uri));
                                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);
                                    bitmap.Save(System.IO.Path.Combine(rom_root,String.Format("{0}.jpg",file_name.Substring(2).Split('.').First())));
                                }
                                break;
                            // Unspecified status codes.
                            default:
                                Console.WriteLine("Unspecified status code found,aborting...");
                                break;
                        }
                    }
                } catch(System.Net.WebException ex)
                {
                    // Should be moved to switch with HttpStatusCode.NotFound ^
                    Console.WriteLine("Image page not found.");
                }

解决方法

这就是GetResponse()实现的方式。如果响应不是成功,则抛出WebException

我同意,我觉得有些奇怪-至少如果它是可选行为,那就太好了。 值得庆幸的是,您可以从正在抛出的WebException中读取状态代码:

....
catch (WebException e)
{
    using (WebResponse response = e.Response)
    {
        HttpWebResponse httpResponse = (HttpWebResponse) response;
        var statusCode = httpResponse.StatusCode;
        // Do stuff with the statusCode
    }
}