Tuesday, April 23, 2013

WCF with REST


What is REST

“Representational State Transfer”. RESTS highlight things like separation of concerns and layers, statelessness, and caching. Using REST, you can get those benefits interoperability, independent evolution, interception, improved scalability, efficiency, and overall performance."
REST usage is different than the normal WSDL based SOAP web service usage. Normally, a WCF service will use SOAP, but if you build a REST service, clients will be accessing your service with a different architectural style such as JSON.
REST uses some common HTTP methods to insert/delete/update/retrieve information which is below:
  1. GET - Requests a specific representation of a resource
  2. PUT - Creates or updates a resource with the supplied representation
  3. DELETE - Deletes the specified resource
  4. POST - Submits data to be processed by the identified resource
What is the Key benefits using REST
·         Reduce the overhead.
·         Less duplication
·         Standardized
·         Great Readability
Let’s Create Restful WCF Service
First open the Visual Studio and create a new WCF Service Application


You can view the file hierarchy as below. Highlighted files are Service file and Interface file.




You can remove the default Service file or you can add your own WCF Service file.



After that, you can define the required service method definition in Service interface as follows.



You have two different methods, one method will return as xml format and other will return as json.

[OperationContract]
        [WebInvoke(Method="Get",ResponseFormat =WebMessageFormat.Xml,
        BodyStyle=WebMessageBodyStyle.Wrapped,UriTemplate="xml/{id}")]
        string GetNamexml(string _id);

        [OperationContract]
        [WebInvoke(Method = "Get", ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/{id}")]
        string GetNamejson(string _id);

 
You can pass multiple parameters as follows,
[OperationContract]
[WebInvoke(Method = "Post", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/{id}/{name}/{address}")]
string SaveDatajson(string _id,string _name,string _address);

Now you are going to implement the Service method in your WCF Service file.

public class SampleRest : ISampleRest
    {

        public string GetNamexml(string _id)
        {
            return "This is my Xml type result " + _id; 
        }

        public string GetNamejson(string _id)
        {
            return "This is my json type result " + _id; 
        }


        public string SaveDatajson(string _id, string _name, string _address)
        {
           //save data to db
            return "ok";
        }
    }





No comments:

Post a Comment