Data Contract in WCF is an agreement between parties (i.e. a service and a client) that describes what type of data will be exchanged between them? On the other hand, Message Contract describes the structure of SOAP messagethatis passed between parties (i.e. a service and a client). Using Data Contract, we actually control the contents (i.e. Payload data or message body) of a SOAP message while Message Contract provides complete control over structure of SOAP message.In Windows Communication Foundation, there are two types of Contracts:
- Behavioral Contracts
- Structural Contracts
DataContract Example:
[DataMember(Name=”LastName“, Order=3)]
- Order = 1,2,3 defines the order of the data member in response message body.
- Name = “some name” dictates the name of particular data member as part of response message body.
MessageContract Example:
Now consider a business scenario, an authentication code is required to access our service i.e. IStudentService. In this case functionality provided by our service will remain the same but authentication code validity is additional pre-requisite now. So in such cases, SOAP message header is the most reasonable place to store the authentication code while calling the service method.
Look into the below implementation of this scenario:
public class StudentInfoRequestMessage
{
[MessageHeader()]
public string AuthCode;
[MessageBodyMember()]
public int StudentId;
}
public class StudentInfoResponseMessage
{
[MessageBodyMember()]
public StudentInfo MyStudentInfo;
}
public interface IStudentService
{
[OperationContract]
StudentInfoResponseMessage GetStudentById(StudentInfoRequestMessage stdInfoMessage);
}
{
public StudentInfoResponseMessage GetStudentById(StudentInfoRequestMessage stdInfoMessage)
{
private const string AuthCode = “ali123salman”;
//Validation Check
if (stdInfoMessage.AuthCode != AuthCode)
{
//fault response
}
//routine code
}
}
Hopefully, now reader will have good understanding about the difference between DataContract and MessageContract in WCF.
Top 10 Interview Questions and Answers Series:
- Top 10 WCF Interview Questions
- Comprehensive Series of WCF Interview Questions
- Top 10 HTML5 Interview Questions
- Top 10 ASP.NET Interview Questions
- Comprehensive Series of ASP.NET Interview Questions
- Top 10 ASP.NET MVC Interview Questions
- Top 10 ASP.NET Web API Interview Questions
- Top 10 ASP.NET AJAX Interview Questions
Really good article ..thanks a lot man … and keep up the good work..
Thanks Rkesh for appreciation.
Soon, you will find a related Complete Online Practice Certification Exam here.
Pingback: 5 simple steps to create your first RESTful service | WCF Tutorial