Click here to Skip to main content
12,814,994 members (41,484 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


53 bookmarked
Posted 30 Oct 2011

Developing WCF Restful Services with GET and POST Methods

, 30 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
How to create WCF REST based service


In this article, we will see how to create WCF REST based service. In this example, we will define two methods, GetSampleMethod (method type is GET) & PostSampleMethod (method type is POST).

  • GET method will take input as String & returns formatted String.
  • POST method will take input as XML (user registration) & return 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 WCF Service
    1. Define Interface
    2. Define Class
    3. Implement POST & GET methods
  2. Define Configuration for WCF Service
    1. Service Configuration
    2. Behavior Configuration
  3. Smoke test WCF service (before client uses it)
  4. Implement client code to use WCF service

Define 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:
    1. OperationContract: PostSampleMethod
    2. WebInvoke Method Type = POST as we are implementing POST
    3. 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
    4. PostSampleMethod will accept XML string as input in POST method. Using Stream as input parameter, we can de-serialize input data before using it.
      [OperationContract(Name = “PostSampleMethod”)]
              [WebInvoke(Method = “POST”,
               UriTemplate = “PostSampleMethod/New”)]
              string PostSampleMethod(Stream data);
    5. OperationContract name: GetSampleMethod
    6. WebGet attribute defined method type is GET
    7. Need to include below namespaces:
    8. System.ServiceModel.Web;
          [OperationContract(Name = “GetSampleMethod”)]
              [WebGet(UriTemplate = “GetSampleMethod/inputStr/{name}”)]
              string GetSampleMethod(string name);
  4. Open MyService.cs class and provide implementation for the methods defined in IMyService Interface as shown below:

    public string PostSampleMethod(Stream data)
            // convert Stream Data to StreamReader
            StreamReader reader = new StreamReader(data);
            // Read StreamReader data as string
            string xmlString = reader.ReadToEnd();
            string returnValue = xmlString;
            // return the XMLString data
            return returnValue;
        public string GetSampleMethod(string strUserName)
            StringBuilder strReturnValue = new StringBuilder();
            // return username prefixed as shown below
    		(”You have entered userName as {0}”, strUserName));
            return strReturnValue.ToString();

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 define webHttpBinding & mexHttpBinding.
  2. In System.ServiceModel defined configuration as shown below. To know details about the below config configuration, check out the URL:
          <service name=”WcfRestBased.MyService” 
    	behaviorConfiguration=”myServiceBehavior” >
            <endpoint name=”webHttpBinding”
            <endpoint name=”mexHttpBinding”

    Service Name: To find what's to be given, right click the service & select ViewMarkup option.

    Example, 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 Service behavior as shown below in System.ServiceModel. “mySeriveBehavior” name should match behaviorConfiguration name defined in Service tag (shown above):
            <behavior name=”myServiceBehavior” >
              <serviceMetadata httpGetEnabled=”true”/>
              <serviceDebug includeExceptionDetailInFaults=”false” />
              <!– 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 name=”webHttp”>

Smoke Test WCF Service

  1. Configure WCF Service in IIS
  2. To check our WCF service is working properly, let's 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 shows 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 WCF Service

  1. Create 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.
    void CallPostMethod()
                // Restful service URL
                string url = 
                // declare ascii encoding
                ASCIIEncoding encoding = new ASCIIEncoding();
                string strResult = string.Empty;
                // sample xml sent to Service & this data is sent in POST
                string SampleXml = @”<parent>” +
                        “<child>” +
  4. Now let's go ahead and implement code to call GETSAMPLEMETHOD from client application. The below code has inline comments:
    void CallGetMethod()
                // Restful service URL
                string url = “http://localhost/wcfrestbased/myservice.svc/
                string strResult = string.Empty;
                // declare httpwebrequet wrt url defined above
                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
                // set method as post
                webrequest.Method = “GET”;
                // set content type
                webrequest.ContentType = “application/x-www-form-urlencoded”;
                // declare & read response from service
                HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
                // set utf8 encoding
                Encoding enc = System.Text.Encoding.GetEncoding(”utf-8?);
                // read response stream from response object
                StreamReader loResponseStream = new StreamReader
    				(webresponse.GetResponseStream(), enc);
                // read string from stream data
                strResult = loResponseStream.ReadToEnd();
                // close the stream object
                // close the response object
                // assign the final result to text box
               txtResult.Text = strResult;
  5. Now go ahead and call the above methods to see the output of each method.

Happy coding… hope this helps!


  • 29th October, 2011: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

You may also be interested in...


Comments and Discussions

Question1 star - incomplete code Pin
Member 1209130627-Oct-15 4:43
memberMember 1209130627-Oct-15 4:43 
GeneralAbove code and Fourthbottle code helped me a lot to know WCF Pin
lawrine7-Oct-15 4:56
memberlawrine7-Oct-15 4:56 
Questionhaving trouble in making this sample Pin
vaibhav_gupta_244-Nov-14 22:37
membervaibhav_gupta_244-Nov-14 22:37 
QuestionGreat Article Pin
nsnavare15-Oct-13 0:54
membernsnavare15-Oct-13 0:54 
Question[My vote of 1] No sample project Pin
msdevtech6-Sep-13 17:17
membermsdevtech6-Sep-13 17:17 
QuestionThank you Pin
suneetha 214-May-13 0:17
membersuneetha 214-May-13 0:17 
GeneralMy vote of 5 Pin
dmikhel2-May-13 4:29
memberdmikhel2-May-13 4:29 
GeneralMy vote of 4 Pin
Masked Dev27-Mar-13 6:00
memberMasked Dev27-Mar-13 6:00 
QuestionVote of 4 Pin
Masked Dev27-Mar-13 5:58
memberMasked Dev27-Mar-13 5:58 
Helped me lots although I did get caught out in my own project...

This worked for me:

<endpoint name="REST"
          binding="webHttpBinding" bindingConfiguration="RESTBinding"

I initially copy&pasted from this article but needed to changed BehaviourConfiguration to BindingConfiguration for my own scenario. Without it, no error but no .svc published...

I probably need specific BehaviourConfigurations too.

Good work mate Smile | :)

Would be five if touched upon a couple more points. Would almost certainly be five if there was just a bit more whitespace in the example. More white lines please!
GeneralVery helpful Pin
Member 410787314-Mar-13 1:13
memberMember 410787314-Mar-13 1:13 
GeneralMy vote of 4 Pin
Kenny Woo10-Sep-12 19:29
memberKenny Woo10-Sep-12 19:29 
QuestionVery Useful Pin
sainulabi4-Jul-12 6:24
membersainulabi4-Jul-12 6:24 
GeneralMy vote of 4 Pin
Ramya.Raju.M28-Jun-12 20:00
memberRamya.Raju.M28-Jun-12 20:00 
OnlineNewby23-Mar-12 6:14
memberOnlineNewby23-Mar-12 6:14 
Bangla Gopal Surya23-Mar-12 8:30
memberBangla Gopal Surya23-Mar-12 8:30 
QuestionInformation is not sufficient for beginners to develop a REST ful WCF Service Pin
raajesshh3-Nov-11 0:21
memberraajesshh3-Nov-11 0:21 
AnswerRe: Information is not sufficient for beginners to develop a REST ful WCF Service Pin
Bangla Gopal Surya3-Nov-11 19:44
memberBangla Gopal Surya3-Nov-11 19:44 
GeneralRe: Information is not sufficient for beginners to develop a REST ful WCF Service Pin
raajesshh4-Nov-11 0:53
memberraajesshh4-Nov-11 0:53 
GeneralRe: Information is not sufficient for beginners to develop a REST ful WCF Service Pin
Mike Gledhill5-Jul-12 10:04
memberMike Gledhill5-Jul-12 10:04 
GeneralLink to a Download for a working version of this project. Pin
Mike Gledhill5-Jul-12 23:36
memberMike Gledhill5-Jul-12 23:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170308.1 | Last Updated 30 Oct 2011
Article Copyright 2011 by Bangla Gopal Surya Prakash
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid