Thursday, 26 December 2013

Create a WCF Rest service with response type xml and json

In article we are going to see how to create a WCF rest service with response type as xml and json. To create REST service three things need to be kept in mind.

1. Endpoint Binding should be webHttpBinding
2. Create  EndPoint behaviour and add <webHttp />
3. Create a UriTemplate and specify the WebGet or WebInvoke attribute

UriTemplate : Specify what kind of uri need to specify to that method
ResponseFormat : Specify the Response Format Xml or Json
Method :   POST or GET


        <behavior name="Restsample.Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        <behavior name="Rest">
          <webHttp />

<endpoint address="" behaviorConfiguration="Rest" binding="webHttpBinding" contract="Restsample.IService1">  

C# code

  public interface IService1
        int Add();

        List<Employee> GetEmployees();

        int AddOperation(int a);

        [WebInvoke(UriTemplate = "/Sub?a={a}&b={b}", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        int SubOperation(int a,int b);


public class Service1 : IService1
        public int Add()
            return 10;

        public List<Employee> GetEmployees()
            List<Employee> employees = new List<Employee>();
            employees.Add(new Employee() { EmpID = 1,EmpName="Rajesh",Address="Chennai"});
            employees.Add(new Employee() { EmpID = 2, EmpName = "Suresh", Address = "Mumbai" });
            employees.Add(new Employee() { EmpID = 3, EmpName = "Ramesh", Address = "Bangalore" });
            employees.Add(new Employee() { EmpID = 4, EmpName = "Siva", Address = "Delhi" });
            employees.Add(new Employee() { EmpID = 5, EmpName = "Farath", Address = "Hyderabad" });
            return employees;

        public int AddOperation(int a)
            return 1 + a;

        public int SubOperation(int a, int b)
            return a + b;

    public class Employee
        public int EmpID { set; get; }

        public string EmpName { set; get; }

        public string Address { set; get; }

Invoke service from browser :

Call a AddOperation method in browser 

output : 2

Following uri will call the Add method

output: 10

Following Uri will call the add employee method





<ArrayOfEmployee xmlns="" xmlns:i="">

From this article we can understand how to create a REST WCF service.

No comments:

Post a Comment