Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebRequest.GetResponse throws WebException on HTTP 304

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?

like image 601
Anton Gogolev Avatar asked Sep 02 '09 10:09

Anton Gogolev


2 Answers

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;     } } 
like image 60
Anton Gogolev Avatar answered Sep 16 '22 20:09

Anton Gogolev


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/

like image 25
Garrett Serack Avatar answered Sep 17 '22 20:09

Garrett Serack