Sunday, November 21, 2010

WCF Contracts


WCF supports following contracts:
1. Service Contract
2. Operation Contract
3. Message Contract
4. Fault Contract

Service Contract: We can use this service contract attribute on interface which will be exposed to client to consume the WCF service.

[ServiceContract]
public interface IStudentContract
{
[OperationContract()]
List GetStudents();

[OperationContract]
Student GetStudent(int studentId);

}

Here we added “ServiceContract” attribute to IStudentContract interface. So WCF will expose this interface as a WCF service.

Operation Contract: We need to use “OperationContract” attribute to the methods which needs to be exposed as a service method. In above example, We have added “OperationContract” attribute to “GetStudents” and “GetStudent” methods.

Message Contract: Sometime we need to change SOAP message format, then we can use Message contract. We can place some variables in body and some in header part as per requirement.

[MessageContract]
public class Student
{
[MessageHeader]
public int StudentId;

[MessageBodyMember]
public string StudentName;

[MessageBodyMember]
public int Standard;
}

Here, student class is decorated as a MessageContract attribute. When we transfer object of student class between client and service then WCF will include “StudentId” attribute to Message Header and “StudentName” and “Standard” attribute in Message Body.

Fault Contract: Fault contract is used to managing fault (exception) in WCF service. You can decorate any class as a Fault contract and send it as an Exception from service to client.

No comments:

Post a Comment

DotNet Code Guru