Developing WCF Restful Services with GET and POST Methods

Here you will see how to create a WCF REST based service. In this example, we will define 2 methods GetSampleMethod (method type is GET) & PostSampleMethod (method type is POST).
  • GET method will take input as String & returns a formatted String
  • POST method will take an input as XML (user registration) & return a status string
Note: One should have basic knowledge of what is WCF, Why WCF & my article will discuss how to use WCF with webHttpBinding
 
We will divide this article into the below sections
  1. Define the WCF Service
    • Define Interface
    • Define Class
    • Implement POST & GET methods
  2. Define a Configuration for the WCF Service
    • Service Configuration
    • Behavior Configuration
  3. Smoke test WCF service (before Client uses it)
  4. Implement client code to use WCF Service

Define the WCF Service

  1. Open VS 2010 & Select new Project, then select WCF & select WCF Service Application & name it as WCF Rest Based.
  2. Now add new Service Class to this application as "MyService.svc"
  3. Open interface IMservice.cs & add the below code
    • OperationContract: PostSampleMethod
    • WebInvoke Method Type = POST as we are implementing POST
    • URI Template defines the URL format by which this method is identified/linked. Note: MethodName, URI Template name & Operation Contract names may not be same means, they can be different
    • PostSampleMethod will accept XML string as input in POST method. Using Stream as input parameter we can de-serialize input data before using it
      1. [OperationContract(Name = "PostSampleMethod")]  
      2. [WebInvoke(Method = "POST",  
      3. UriTemplate = "PostSampleMethod/New")]  
      4. string PostSampleMethod(Stream data);
    • OperationContract name : GetSampleMethod
    • WebGet attribute defined method type is GET
    • Need to include below namespaces
    1. using System.ServiceModel.Web;  
    2. using System.ServiceModel  
    3. using System.Runtime.Serialization  
    4. using System.IO  
    5. [OperationContract(Name = "GetSampleMethod")]  
    6. [WebGet(UriTemplate = "GetSampleMethod/inputStr/{name}")]  
    7. string GetSampleMethod(string name);
  4. Open the MyService.cs class and provide implementation for the methods defined in IMyService Interface as shown below
    1. publicstring PostSampleMethod(Stream data) {  
    2.  // convert Stream Data to StreamReader  
    3.  StreamReader reader = new StreamReader(data);  
    4.   
    5.  // Read StreamReader data as string  
    6.  string xmlString = reader.ReadToEnd();  
    7.  string returnValue = xmlString;  
    8.   
    9.  // return the XMLString data  
    10.  return returnValue;  
    11. }  
    12. public string GetSampleMethod(string strUserName) {  
    13.  StringBuilder strReturnValue = new StringBuilder();  
    14.  // return username prefixed as shown below  
    15.  strReturnValue.Append(string.Format("You have entered userName as {0}", strUserName));  
    16.  return strReturnValue.ToString();  
    17. }

Define Configuration for WCF Service

  1. Open web.config as we need to define configuration for our WCF Service. If you want our service to be accessed as part of webHttp then we need to defined webHttpBinding & mexHttpBinding.
  2. In System.ServiceModel defined configuration as shown below. 
    1. <services>  
    2.       <servicename="WcfRestBased.MyService"  
    3.          behaviorConfiguration="myServiceBehavior">  
    4.         <endpointname="webHttpBinding"  
    5.                   address=""  
    6.                   binding="webHttpBinding"  
    7.                   contract="WcfRestBased.IMyService"  
    8.                   behaviorConfiguration="webHttp"  
    9.                   >  
    10.                 </endpoint>  
    11.         <endpointname="mexHttpBinding"  
    12.                   address="mex"  
    13.                   binding="mexHttpBinding"  
    14.                   contract="IMetadataExchange"  
    15.                   />  
    16.       </service>  
    17. </services>
    Service Name: To find what to be given, then right click the service & select ViewMarkup option.eg in my case it is MyService.svc, look for Service attribute & use the complete string in my case it is Service="WcfRestBased.MyService"behaviorConfiguration: can be any name but this will be again used when we define behavior settings in my case it is myServiceBehavior

    Endpoint for webHttpBinding

    endpoint name: should be webHttpBinding if you are configuring for web access

    address: we can leave it empty

    binding: should be webHttpBinding

    contract: should be Namespace.Interfacename. In my case it is wcfRestBased.IMyService

    behaviorConfiguration: should be webHttp

    EndPoint for mexHttpBinding

    These values should be same as shown above
  3. Now define the Service behavior as shown below in System.ServiceModel. "mySeriveBehavior" name should match to behaviorConfiguration name defined in Service tag ( shown above)
    1. <behaviors>  
    2.       <serviceBehaviors>  
    3.         <behavior name="myServiceBehavior" >  
    4.           <serviceMetadata httpGetEnabled="true"/>  
    5.           <serviceDebug includeExceptionDetailInFaults="false" />  
    6.         </behavior>  
    7.         <behavior>  
    8.           <!– To avoid disclosing metadata information,   
    9.                  set the value below to false and remove the metadata endpoint   
    10.                  above before deployment –>  
    11.           <serviceMetadata httpGetEnabled="true"/>  
    12.           <!– To receive exception details in faults for debugging purposes,   
    13.                  set the value below to true. Set to false before deployment   
    14.                  to avoid disclosing exception information –>  
    15.           <serviceDebug includeExceptionDetailInFaults="false"/>  
    16.         </behavior>  
    17.       </serviceBehaviors>  
    18.       <endpointBehaviors>  
    19.         <behavior name="webHttp">  
    20.           <webHttp/>  
    21.         </behavior>  
    22.       </endpointBehaviors>  
    23. </behaviors>

Smoke test WCF service

  1. Configure WCF Service in IIS
  2. To check our WCF service is working properly lets test it by opening MyService.svc in browser in my case it is http://localhost/wcfrestbased/MyService.svc
  3. To test our GET method service, you can call it by http://localhost/wcfrestbased/MyService.svc/GetSampleMethod/inputStr/suryaprakash & this show up data as "<string>You have entered userName as suryaprakash</string>"
  4. By this we can confirm our service is working fine

Implement client code to use the WCF Service

  1. Create a new website application which will act as client to access WCF services
  2. Add a textbox to default.aspx page & name it as txtResult & open Default.aspx.cs
  3. Define below function which will call rest service to fetch the data. This method will call POSTSAMPLEMETHOD in service (MyService) implemented. Inline code comments are added
    1. void CallPostMethod() {  
    2.   // Restful service URL  
    3.   string url ="http://localhost/wcfrestbased/myservice.svc/PostSampleMethod/New";  
    4.   
    5.   // declare ascii encoding  
    6.   ASCIIEncoding encoding = new ASCIIEncoding();  
    7.   string strResult = string.Empty;  
    8.   // sample xml sent to Service & this data is sent in POST  
    9.   string SampleXml = @ "<parent>" +  
    10.    "<child>" +  
    11.    "<username>username</username>" +  
    12.    "<password>password</password>" +  
    13.    "</child>" +  
    14.    "</parent>";  
    15.   string postData = SampleXml.ToString();  
    16.   // convert xmlstring to byte using ascii encoding  
    17.   byte[] data = encoding.GetBytes(postData);  
    18.   // declare httpwebrequet wrt url defined above  
    19.   HttpWebRequest webrequest = (HttpWebRequest) WebRequest.Create(url);  
    20.   // set method as post  
    21.   webrequest.Method = "POST";  
    22.   // set content type  
    23.   webrequest.ContentType = "application/x-www-form-urlencoded";  
    24.   // set content length  
    25.   webrequest.ContentLength = data.Length;  
    26.   // get stream data out of webrequest object  
    27.   Stream newStream = webrequest.GetRequestStream();  
    28.   newStream.Write(data, 0, data.Length);  
    29.   newStream.Close();  
    30.   // declare & read response from service  
    31.   HttpWebResponse webresponse = (HttpWebResponse) webrequest.GetResponse();  
    32.   
    33.   // set utf8 encoding  
    34.   Encoding enc = System.Text.Encoding.GetEncoding("utf-8?);  
    35.    // read response stream from response object  
    36.    StreamReader loResponseStream =  
    37.    new StreamReader(webresponse.GetResponseStream(), enc);  
    38.    // read string from stream data  
    39.    strResult = loResponseStream.ReadToEnd();  
    40.    // close the stream object  
    41.    loResponseStream.Close();  
    42.    // close the response object  
    43.    webresponse.Close();  
    44.    // below steps remove unwanted data from response string  
    45.    strResult = strResult.Replace("</string>""");  
    46. }
  4. Now lets go ahead and implement code to call GETSAMPLEMETHOD from client application. Below code has inline comments
    1. void CallGetMethod() {  
    2.   // Restful service URL  
    3.   string url = "http://localhost/wcfrestbased/myservice.svc/  
    4.   GetSampleMethod / inputStr / suryaprakash ";  
    5.   string strResult = string.Empty;  
    6.   // declare httpwebrequet wrt url defined above  
    7.   HttpWebRequest webrequest = (HttpWebRequest) WebRequest.Create(url);  
    8.   // set method as post  
    9.   webrequest.Method = "GET";  
    10.   // set content type  
    11.   webrequest.ContentType = "application/x-www-form-urlencoded";  
    12.   // declare & read response from service  
    13.   HttpWebResponse webresponse = (HttpWebResponse) webrequest.GetResponse();  
    14.   // set utf8 encoding  
    15.   Encoding enc = System.Text.Encoding.GetEncoding("utf-8?);  
    16.    // read response stream from response object  
    17.    StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);  
    18.    // read string from stream data  
    19.    strResult = loResponseStream.ReadToEnd();  
    20.    // close the stream object  
    21.    loResponseStream.Close();  
    22.    // close the response object  
    23.    webresponse.Close();  
    24.    // assign the final result to text box  
    25.    txtResult.Text = strResult;  
    26. }
  5. Now go ahead and call above methods to see the output of each methods.
Happy coding, Hope this helps!


Similar Articles