I am in a situation where when I get an HTTP 400 code from the server, it is a completely legal way of the server telling me what was wrong with my request (using a message in the HTTP response content)
However, the .NET HttpWebRequest raises an exception when the status code is 400.
How do I handle this? For me a 400 is completely legal, and rather helpful. The HTTP content has some important information but the exception throws me off my path.
I had similar issues when trying to connect to Google's OAuth2 service.
I ended up writing the POST manually, not using WebRequest, like this:
The response that gets written to the response stream contains the specific error text that you're after.
In particular, my problem was that I was putting endlines between url-encoded data pieces. When I took them out, everything worked. You might be able to use a similar technique to connect to your service and read the actual response error text.
An asynchronous version of extension function:
Try this (it's VB-Code :-):
It would be nice if there were some way of turning off "throw on non-success code" but if you catch WebException you can at least use the response:
You might like to encapsulate the "get me a response even if it's not a success code" bit in a separate method. (I'd suggest you still throw if there isn't a response, e.g. if you couldn't connect.)
If the error response may be large (which is unusual) you may want to tweak
HttpWebRequest.DefaultMaximumErrorResponseLength
to make sure you get the whole error.I know this has already been answered a long time ago, but I made an extension method to hopefully help other people that come to this question.
Code:
Usage:
Interestingly, the
HttpWebResponse.GetResponseStream()
that you get from theWebException.Response
is not the same as the response stream that you would have received from server. In our environment, we're losing actual server responses when a 400 HTTP status code is returned back to the client using theHttpWebRequest/HttpWebResponse
objects. From what we've seen, the response stream associated with theWebException's HttpWebResponse
is generated at the client and does not include any of the response body from the server. Very frustrating, as we want to message back to the client the reason for the bad request.