Sunday, February 19, 2012

WCF REST POST Example

In this article i will demonstrate simple Windows Communication Foundation (WCF) 3.5 Rest example which uses Http POST  which consumes Json Object and returns Json object.


Windows Communication Foundation is a part of the .NET Framework that provides a unified programming model for rapidly building service-oriented applications (SOA) that communicate across the web and the enterprise.Following classes are of great interest when programming REST services



WebGetAttribute – Handling the GET HTTP Verb
WebInvokeAttribute – Handling the other HTTP Verbs (POST, DELETE, PUT). 
WebHttpBinding – The WCF binding that ties it together.
WebServiceHost – An extension of the ServiceHost class for hosting REST Services.


In WCF Custom data types are represented using DataContract and fields are represented using DataMember in DataContract.cs



[DataContract]
public class DataContract
{
    [DataMember]
    public string name;
    [DataMember]
    public int age;
    [DataMember]
    public string location;
}
Define the following operation in the Interface
[OperationContract]
[WebInvoke(
    Method = "POST", 
    UriTemplate = "person", 
    ResponseFormat=WebMessageFormat.Json, 
    RequestFormat=WebMessageFormat.Json)]
string CreatePerson(Person person);
}

public class Person: Iperson
 {
    public string CreatePerson(Person person)
     {
        return "Name : " + person.name + "Age : " + person.age + "location : "+ person.location;
     }
 }
Http Method is POST so we cannot use browser to send post message so use fiddler to send post message.







to send this request click execute button. WCF Rest service will return the json response for the person raghu.

1 comment:

Sreekanth.K said...

Class name should be Person instead of DataContract, I think it is a mistake from your side.

Popular Posts