Tuesday, February 19, 2013

WCF Rest example

Create a WCF Service, Delete the default added service and follow the steps below.

Step 1: Create a object called Student, this object we use in our example


 [DataContract]
    public class Student
    {
        [DataMember]
        public int StudentId { get; set; }

        [DataMember]
        public int ClassId { get; set; }

        [DataMember]
        public string Firstname { get; set; }

        [DataMember]
        public string Lastname { get; set; }
    }

Now create a WCF service with any business name as per your requirement, here i have created a service called RestfulServiceExample.svc , open the interface created with name IRestfulServiceExample, here i have added four example of Json and XML with single object and collection object

Here is how the definition would look like.

using System.ServiceModel;
using System.ServiceModel.Web;
using WcfRestExample.BusinessObjects;
using System.Collections.Generic;

namespace WcfRestExample
{

    [ServiceContract(Namespace = "http://arindamachakraborty.blogspot.in")]
    public interface IRestfulServiceExample
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Xml,
            RequestFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "xml/{id}")]
        Student XMLStudent(string id);


        [OperationContract]
        [WebInvoke(Method = "GET",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Wrapped,
           UriTemplate = "json/{id}")]
        Student JSONStudent(string id);


        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Xml,
            RequestFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "xmls/{id}")]
        List XMLStudents(string id);


        [OperationContract]
        [WebInvoke(Method = "GET",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Wrapped,
           UriTemplate = "jsons/{id}")]
        List JSONStudents(string id);
    }
}

Note : in WebInvoke attribute Method value is case sensitive, that should always be  Method = "GET", not Method = "Get" or Method = "get"

Now lets look at the implementation of interface.


public class RestfulServiceExample : IRestfulServiceExample
    {

        public Student JSONStudent(string id)
        {
            return new Student()
            {
                ClassId = 1,
                StudentId = 2,
                Firstname = "Arindam",
                Lastname = "Chakraborty"
            };
        }

        public Student XMLStudent(string id)
        {
            return new Student()
            {
                ClassId = 1,
                StudentId = 2,
                Firstname = "Arindam",
                Lastname = "Chakraborty"
            };
        }


        public List< Student > XMLStudents(string id)
        {
            List< Student > students = new List< Student >();
            students.Add(new Student(){ ClassId=1, Firstname="Arindam", Lastname="Chakraborty", StudentId=1 });
            students.Add(new Student() { ClassId = 2, Firstname = "Richa", Lastname = "Pandit", StudentId = 2 });
            students.Add(new Student() { ClassId = 3, Firstname = "Soham", Lastname = "Khanna", StudentId = 3 });


            return students;
        }

        public List< Student > JSONStudents(string id)
        {
            List< Student  > students = new List< Student >();
            students.Add(new Student() { ClassId = 1, Firstname = "Arindam", Lastname = "Chakraborty", StudentId = 1 });
            students.Add(new Student() { ClassId = 2, Firstname = "Richa", Lastname = "Pandit", StudentId = 2 });
            students.Add(new Student() { ClassId = 3, Firstname = "Soham", Lastname = "Khanna", StudentId = 3 });
         
            return students;
        }
    }

We are done with service development, now we look at service configuration and how to publish

< system.serviceModel >
    < services >
      < service name="WcfRestExample.RestfulServiceExample" behaviorConfiguration="ServiceBehavior" >
        < endpoint  binding="webHttpBinding"
                  contract="WcfRestExample.IRestfulServiceExample"
                  behaviorConfiguration="web" >
        < /endpoint >
      < /service >
    < /services >

Notice we have set binding="webHttpBinding"

    < behaviors >
      < serviceBehaviors >
        < behavior name="ServiceBehavior" >
          < !-- To avoid disclosing metadata information,
          set the value below to false
          and remove the metadata endpoint above before deployment -- >
          < serviceMetadata httpGetEnabled="true"/ >
          < !-- To receive exception details in faults for
          debugging purposes, set the value below to true.
          Set to false before deployment to avoid disclosing
          exception information -- >
          < serviceDebug includeExceptionDetailInFaults="false"/ >
        < /behavior >
      < /serviceBehaviors >
      < endpointBehaviors >
        < behavior name="web" >
          < webHttp / >
        < /behavior >
      < /endpointBehaviors >
    < /behaviors >
    < serviceHostingEnvironment multipleSiteBindingsEnabled="true" / >
  < /system.serviceModel >

Now we have successfully built and published the service, so its time to test the service, so you can see how the end result will look like.

Here is the url you need to run
http://machinename/servicename/xml - xml output for single objetc
http://machinename/servicename/xmls - xml output for collection object
http://machinename/servicename/json - json single object
http://machinename/servicename/jsons -  json output collection objects

No comments:

ETG Consultancy

Web Designing Development Analysis & Promotion
Asp.Net 2.0 SQL WWF WCF SEO Marketing Ajax JQuery NHibernate MVC