When a web server responds to HttpWebRequest.GetResponse()
with HTTP 304 (Not Modified), GetResponse()
thows a WebException
, which is so very weird to me. Is this by design or am I missing something obvious here?
Ok, this seems to be a by-design behavior and a perfect example of a vexing exception. This can be solved with this:
public static HttpWebResponse GetHttpResponse(this HttpWebRequest request) { try { return (HttpWebResponse) request.GetResponse(); } catch (WebException ex) { if(ex.Response == null || ex.Status != WebExceptionStatus.ProtocolError) throw; return (HttpWebResponse)ex.Response; } }
This is really a frustrating problem, and can be alternatively worked around by using the following extension method class and calling request.BetterGetResponse()
//----------------------------------------------------------------------- // // Copyright (c) 2011 Garrett Serack. All rights reserved. // // // The software is licensed under the Apache 2.0 License (the "License") // You may not use the software except in compliance with the License. // //----------------------------------------------------------------------- namespace CoApp.Toolkit.Extensions { using System; using System.Net; public static class WebRequestExtensions { public static WebResponse BetterEndGetResponse(this WebRequest request, IAsyncResult asyncResult) { try { return request.EndGetResponse(asyncResult); } catch (WebException wex) { if( wex.Response != null ) { return wex.Response; } throw; } } public static WebResponse BetterGetResponse(this WebRequest request) { try { return request.GetResponse(); } catch (WebException wex) { if( wex.Response != null ) { return wex.Response; } throw; } } } }
You read more about it in my blog post on this subject at http://fearthecowboy.com/2011/09/02/fixing-webrequests-desire-to-throw-exceptions-instead-of-returning-status/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With