Is there a way to change the behavior of HttpWebRequest to 400/500 status codes?

I am working on creating a free REST client interface on top of the HttpWebRequest / HttpWebResponse in .NET. So far so good ... however, I'm trying to develop a pluggable security infrastructure that can automatically handle security token approvals, token updates, etc.

I had a problem due to the nature of the HttpWebRequest/Response operation when they encounter a 400 or 500 series HTTP status code. Instead of just setting the .StatusCode and .StatusDescription and letting you handle anything, they throw a WebException . Generally speaking, this is probably not a problem ... however, as we authenticate (derived from OAuth 2.0), I need to handle some 400 series errors without throwing an exception.

Is there a way to reconfigure HttpWebRequest / Response so as NOT to throw a WebException and allow the consumer to define their own error handling? I know that there are several ways to interact with Expect-100-Continue with older Http1.0 servers ... I am curious if there is a similar way to disable WebExceptions around a round.

(Oh, and I just can't help it ... BIG CONDUCTOR RELATED to my WONDERFUL friends at RedGate for illegally alienating the FREE License-related version of Reflector 6 ... Maybe I can one of my own if I could hide code ... but alas ... Reflector, unfortunately, is an unviable option now that it has absorbed itself through autolysis .; P)

+7
source share
1 answer

I had a similar problem and it was solved using the following helper method:

 public static HttpWebResponse MakeRequest(HttpWebRequest request) { try { return (HttpWebResponse)request.GetResponse(); } catch (WebException we) { if (we.Response != null) { return (HttpWebResponse)we.Response; } throw; } } 
+8
source

All Articles