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?
views:
623answers:
1
+4
A:
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;
}
}
Anton Gogolev
2009-09-02 10:17:04
This works most of the cases, but some web servers could return a response body when returning a 404 error. In that case, the code above would treat a 404 as it treats a 304!
comshak
2010-01-07 20:50:36