Tuesday, June 4, 2013

Using of Message Contract in Asp.net WCF | Message Contract Example in asp.net | Using Message Contract along with Data Contract

hi in this post i will show and basic example of using message contract in WCF asp.net.

Message Contract : It is used to control the details inside the SOAP Header and Body.

Example:

1. This is how my solution explorer look like:

2. Interface code i.e. IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService5
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        EmpDetails GetDataUsingDataContract(EmpID EmpObj);
    }

    [DataContract]
    public class Employee
    {
        [DataMember(Name = "Name", Order = 1)]
        public string EmpName;

        [DataMember(Name = "Salary", Order = 2)]
        public string Salary;

    }

    [MessageContract(IsWrapped = false)]
    public class EmpID
    {
        [MessageHeader]
        public string Id;
    }

    [MessageContract(IsWrapped = false)]
    public class EmpDetails
    {
        [MessageBodyMember]
        public Employee Emp;
    }
}

3. Service1.svc.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService5
{
    public class Service1 : IService1
    {
        public EmpDetails GetDataUsingDataContract(EmpID EmpObj)
        {
            EmpDetails EmpDetailsObj = new EmpDetails();
            EmpDetailsObj.Emp = new Employee();

            if (EmpObj.Id == "0")
            {
                EmpDetailsObj.Emp.EmpName = "NA";
                EmpDetailsObj.Emp.Salary = "NA";
                return EmpDetailsObj;
            }
            else
            {
                EmpDetailsObj.Emp.EmpName = "Chandan";
                EmpDetailsObj.Emp.Salary = "10000";
                return EmpDetailsObj;
            }

        }
    }
}

4. Results:






No comments:

Post a Comment