Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error detail from WCF REST

I have a REST service consumed by a .Net WCF client.

When an error is encountered the REST service returns an HTTP 400 Bad Request with the response body containing JSON serialised details.

If I execute the request using Fiddler, Javascript or directly from C# I can easily access the response body when an error occurs.

However, I'm using a WCF ChannelFactory with 6 quite complex interfaces. The exception thrown by this proxy is always a ProtocolException, with no useful details.

Is there any way to get the response body when I get this error?


Update

I realise that there are a load of different ways to do this using .Net and that there are other ways to get the error response. They're useful to know but don't answer this question.

The REST services we're using will change and when they do the complex interfaces get updated. Using the ChannelFactory with the new interfaces means that we'll get compile time (rather than run time) exceptions and make these a lot easier to maintain and update the code.

Is there any way to get the response body for an error HTTP status when using WCF Channels?

like image 712
Keith Avatar asked Mar 25 '10 15:03

Keith


2 Answers

you can retrieve the exception detail as below:

                Exception innerException = exception.InnerException;
                WebException webException = innerException as WebException;
                HttpWebResponse response = webException.Response as HttpWebResponse;
                string statusDescription = response.StatusDescription;
                HttpStatusCode statusCode = response.StatusCode;
like image 196
Oak Avatar answered Oct 24 '22 07:10

Oak


The InnerException of the ProtocolException will be a WebException. You can get the HttpWebResponse from that and call GetResponseStream to read the actual response body. (Remember to seek to the beginning of the stream before reading).

var webException = (WebException) protocolException.InnerException;
var response = (HttpWebResponse) webException.Response;
var responseStream = response.GetResponseStream()
responseStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(responseStream);
var responseContent = reader.ReadToEnd();
like image 45
JacquesB Avatar answered Oct 24 '22 05:10

JacquesB