Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Fault Contracts in WCF

0.00/5 (No votes)
18 Sep 2011 1  
WCF provides us a facility to specify the fault behavior of our service. It provides a FaultException Class. Whenever our service implementation

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

WCF provides us a facility to specify the fault behavior of our service. It provides a FaultException Class. Whenever our service implementation throws a fault exception, the WCF takes care of serializing that back to the consumer as a SOAP fault. WCF takes care of when our service might issue faults and what type of information will be sent with the fault.

 

[ServiceContract]

public interface IMyFirstService  {

[OperationConract]

[FaultContract( typeof MyAppFault)) ]

void MyMethod();

]


WCF FaultException Class comes in two forms:-

1.FaultException: Used to send untyped data back to the consumer.

2.FaultException<TDetail> : It is used to send typed fault data back  to the consumer. Here TDetail represents the type parameter for the detailed fault information to be serialized back to the consumer as a part of the SOAP fault message. Client catching the exception can access the detailed fault information by getting it from the exception object’s Detail property.


FaultContractAttribute property defined in the System.ServiceModel. It enables the service developer to declare which faults a given service might issue. These attributes can be applied to the operations only. It can be applied multiple times, Suppose if our service operation might return different types of faults, we would have a FaultContractAttribute Declaration for each type. 

It uses a Type object, used to reference the .NET type of the Details object. This is the type of fault information which we want to bundle with our faults.


A Simple example:

[ServiceContract()]

public interface ICalcService

{

    [OperationContract]

[FaultContract( typeof(string))]

double Divide(double numerator, double denominator)

        }

public class CalcService :  ICalcService 

{

public double Divide(double numerator, double denominator)

{

if(denominator ==0.0d)

{

string faultDetail= ”you can not divide it by Zero”l

throw new FaultException<string>(faultDetail);

}

return numerator/denominator;

}

}

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here