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

1

7

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 )

Stale answered 6/5, 2011 at 22:16 Comment(1)
As far as Reflector goes, try using ILSpy.Synapse
C
8

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;
    }
}
Callable answered 8/6, 2011 at 12:52 Comment(1)
Thanks for the answer. I eventually ended up doing pretty much the same thing. I'm not sure why Microsoft chose to force users to catch an exception in the event of an error type status code...but it really makes things difficult. Nice little helper...might try making it an extension method on HttpWebRequest though...makes it easier to use. ;)Stale

© 2022 - 2024 — McMap. All rights reserved.