Wednesday 5 June 2013

Create And Consume WCF REST Service

 Create REST Service using WCF

 1. Open Visual Studio and create a new WCF Service Application and name the project as WcfRest.

 2.  Define Data Contract and Service Contact in IService1.cs. Note RequestFormat and ResponseFormat is Json as we want our service to return and accept Json.  WebGet attribute is used to specify that method will be available through REST call.  You can use [WebInvoke(Method ="Post"] attribute we you want to send updated data to the server. UriTemplate defines how Url will be mapped with service method.

3. Implement Service Contract. Open Service1.svc.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 WcfREST
{
public class Service1 : IService1
{
        List<Person> persons = new List<Person>();
        public string GetDateTime()
        {
            return System.DateTime.Today.ToString();
        }


        public List<Person> GetAllPerson()
        {
            Person obj1 = new Person();
            obj1.Age = 21;
            obj1.ID = 2;
            obj1.Name = "ABC";

            persons.Add(obj1);

            return persons.ToList();
        }
    }
}
4. Specify webHttpBinding and endpoints in Web.config file
<system.serviceModel>
    <services>
      <service name="WcfREST.Service1" behaviorConfiguration="ServiceBehaviour">
          <endpoint address ="" binding="webHttpBinding" contract="WcfREST.IService1" behaviorConfiguration="web">
          </endpoint>

      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <
webHttp/>
        </behavior>

      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

5. Now we can compile and test the service
       http://localhost:53810/Service1.svc/GetAllPerson
Consuming REST service in ASP.NET web application project :

 1. Add following namespaces in the class were you want to communicate with REST service as we will deserialize the Json response into Person class using DataContractJsonSerializer.    
   using System.ServiceModel;
   using System.ServiceModel.Web;
   using System.Runtime.Serialization.Json;
  (You may require to add reference to System.ServiceModel.Web and System.Web.Extensions dll in the project as Serialization.Json may not be available by default)


2. Create a Person class into which we will deserialize the Json response from calling GetAllPerson of REST service
     public class Person 
    {
      public int ID;
      public string Name;
      public int Age;
     }

3.  Now to call REST service and read response we will use WEBClient object :


    WebClient objClient = new WebClient();
    byte[] data = objClient.DownloadData("http://localhost:53810/Service1.svc/Persons");
    Stream st = new MemoryStream(data);

    DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Person>));
    List<Person> result = (List<Person>)obj.ReadObject(st);
    Response.Write(result[0].Name);

No comments:

Post a Comment