Getting error detail from WCF REST

孤人 提交于 2019-12-05 02:01:04

Don't use ChannelFactory :-) Seriously though. Why would you create a REST interface and then use the WCF client proxy. What is the benefit of using the REST service? Why not just use wsHttpBinding? With the HttpClient class from the REST starter kit you can make standard HTTP requests and then deserialize the response using the DataContractSerializer.

E.g.

var httpClient = new HttpClient();
var content = httpClient.Get("http://example.org/customer/45").Content;
var customer = content.ReadAsDataContract<Customer>()

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;

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();

You could try throwing a WebProtocolException from the service. This way the error details should be included in the body of the HTTP response. Have a look at this article:

Effective Error Handling with WCF & REST

My two cents is that WCF is good at exposing the same class using many different bindings. When communicating with C#, use a SOAP binding that is good at exception information. If you must use the REST style binding, you could use a simple WebRequest to call the service and use the JSON serializer to deserialize the results. This will also give you direct access to the response code.

The approach described by user653761 works for me; after having access to the HttpWebResponse object I can use the DataContractSerializer class like this:

var serializer = new DataContractSerializer(typeof(MyDataContractType));
var deserialized = 
    (serializer.ReadObject(httpWebResponse.GetResponseStream()) as MyDataContractType);

// ...

I guess this would work for anything that WCF can serialize if you use the right serializer, didn't test for performance (yet).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!