WCF Service and WebChannelFactory Service Error Handling

In my understanding, the following should correctly throw the user error from the WCF Rest service:

[DataContract(Namespace = "")]
public class ErrorHandler
{
    [DataMember]
    public int errorCode { get; set; }

    [DataMember]
    public string errorMessage { get; set; }
} // End of ErrorHandler

public class Implementation : ISomeInterface
{
    public string SomeMethod()
    {
        throw new WebFaultException<ErrorHandler>(new ErrorHandler()
        {
            errorCode = 5,
            errorMessage = "Something failed"
        }, System.Net.HttpStatusCode.BadRequest);
    }
}

In Fiddler this works, I get the following source data:

HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Length: 145
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Set-Cookie: ASP.NET_SessionId=gwsy212sbjfxdfzslgyrmli1; path=/; HttpOnly
X-Powered-By: ASP.NET
Date: Thu, 03 May 2012 17:49:14 GMT

<ErrorHandler xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><errorCode>5</errorCode><errorMessage>Something failed</errorMessage></ErrorHandler>

But now on my client side there is the following code:

WebChannelFactory<ISomeInterface> client = new WebChannelFactory<ISomeInterface>(new Uri(targetHost));

ISomeInterface someInterface = client.CreateChannel();
try
{
  var result = someInterface.SomeMethod();
}
catch(Exception ex)
{
   // Try to examine the ErrorHandler to get additional details.
}

Now, when the code runs, it gets into catch and presents System.ServiceModel.ProtocolExceptionwith the message “The remote server returned an unexpected response: (400)“ Bad request. ”It seems that I have no way to see the details of the ErrorHandler at this stage. Has anyone encountered this? Is there any way to get ErrorHander data at the moment?

+5
source share
1 answer

WebChannelFactory ChannelFactory CommunicationException. IClientMessageInspector WebRequest, .

IClientMessageInspector . .

WebRequest : WebException.

try { }
catch (Exception ex)
{
    if (ex.GetType().IsAssignableFrom(typeof(WebException)))
    {
        WebException webEx = ex as WebException;
        if (webEx.Status == WebExceptionStatus.ProtocolError)
        {
            using (StreamReader exResponseReader = new StreamReader(webEx.Response.GetResponseStream()))
            {
                string exceptionMessage = exResponseReader.ReadToEnd();
                Trace.TraceInformation("Internal Error: {0}", exceptionMessage);
            }
        }
    }
}
+4

All Articles