Tuesday, June 12, 2012

Fault Contracts in WCF

* Fault Contracts are used to send exception information from a service to client.

* Every information that passes between service and clients must be serialized. Hence this exception information that is required to be passed to client must be of serializable type or it must be a defined data contract which can hold information about exception.

* Fault contracts are used in release environment. This is to make sure clients do not get to see internal implementation of service through exception details.

* When we need all exception details to be passed on to client for debugging or development purposes then we can set includeExceptionDetailsInFaults="true" instead of using fault contract. All we need is to set this attribute in service behavior defined for service endpoint to get all the details of exception at client side. Client has to handle these non-generic exceptions in its code.

<behaviors>
  <serviceBehaviors>
    <behavior name="MyServiceBehavior">
      <serviceMetadata httpGetEnabled="True"/>
      <serviceDebug includeExceptionDetailInFaults="True" />
    </behavior>
  </serviceBehaviors>
</behaviors>

*Every OperationContract that might raise the Fault exception must define the type of the exception in its attribute. 
[OperationContract]
[FaultContract(typeof(UploadFault))]
void UploadData(byte [] data);

Exception Type Defined:

[DataContract]
public class UploadFault
{    
    private string message
    private string errorType;

    [DataMember]
    public string ErrorMessage
    {
        get { return messasge; }
        set { message = value; }
    }

    [DataMember]        
    public string ErrorType
    {
        get { return errorType; }
        set { errorType = value; }
    }
}



No comments:

Post a Comment