Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am working on building a fluent REST client interface on top of the HttpWebRequest/HttpWebResponse types in .NET. So far, so good...however I am trying to develop a pluggable security framework that can automatically handle security token negotiation, token refreshes, etc.

I've run into a problem due to the nature of how HttpWebRequest/Response work when they encounter a 400 series or 500 series HTTP status code. Rather than simply setting the .StatusCode and .StatusDescription properties and allowing you to handle in whatever way you wish, they throw a WebException. Generally speaking, this probably isn't a problem...however the way we are authenticating (derivative of OAuth 2.0), I need to handle certain 400 series errors without an exception occurring.

Is there some way to reconfigure HttpWebRequest/Response to NOT throw WebException, and allow the consumer to determine their own error handling? I know that there are some round-about ways of handling Expect-100-Continue with older Http1.0 servers...I'm curious if there is a similar round-about way to disable WebExceptions.

(Oh, and just can't resist...a BIG OL' SHOUT OUT to my WONDERFUL friends over at RedGate for illegally taking away the license-bound FREE version of Reflector 6...I might be able to figure this one out on my own if I could snoop the code...but alas...Reflector is sadly an nonviable option now that it has consumed itself via autolysis. ;P )

like image 562
jrista Avatar asked May 06 '11 22:05

jrista


1 Answers

I had a similar problem and solved it with 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;
    }
}
like image 141
Kyberias Avatar answered Sep 28 '22 03:09

Kyberias