This is a mirror of official site: http://jasper-net.blogspot.com/

WCF ExceptionHandling in Silverlight

| Thursday, April 7, 2011
I have recently done some LOB application development in Silveright in which we used a WCF service to communicate to the backend. There was an unexpected surprise that Exceptions throw in the WCF service were not transferred to the Silverlight Client! In Silverlight you always get a System.ServiceModel.CommunicationException: The remote server returned an error: NotFound.... error. We wanted to have the server Exception available at the  Silverlight client or at least the error message. (NOTE for security reasons you might not want to send all error information back to the client).

Silverlight version 3 enables support for the Windows Communication Foundation (WCF) SOAP fault, but I could not find any complete simple working examples on the Internet so here a working example.

First we have to change the default HTTP Code for a Fault message from 500 to 200 otherwise the Silverlight client cannot handle them. Use this attribute, also see http://msdn.microsoft.com/en-us/library/dd470096(VS.96).aspx

public class WcfSilverlightFaultBehavior : IDispatchMessageInspector
    {
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (reply.IsFault)
            {
                HttpResponseMessageProperty property = new HttpResponseMessageProperty();

                // Here the response code is changed to 200.
                property.StatusCode = System.Net.HttpStatusCode.OK;

                reply.Properties[HttpResponseMessageProperty.Name] = property;
            }
        }

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            // Do nothing to the incoming message.
            return null;
        }
    }

Posted via email from Jasper-net

0 comments: