Saturday, July 11, 2015

RESTful API using WCF Services



In this article, we will discuss about the concept how we can use WCF services to create a REST based service. We will not go into the details about what is REST architecture style. As per it's type, our service will be of nature, where each method will act as a resource on the internet. So in order to create a REST based service, we will create a new ASP.Net project and add a WCF service project into it. Let's call it RESTService.

Next, we remove any default methods. We add a sample class named POCOClass with 2 properties of Name and Id. Next we add a method in the service, which returns a list of the type POCOClass.

Next, in order to make this service a RESTful type, we need to do some code changes. These include:
  1. Add WebGet attribute or WebInvoke attribute to the methods to allow them to be used with HTTP verbs like GET, PUT, POST etc.
  2. Add a Uri template to these methods, which is nothing but a url which will identify the methods as a unique resource on the internet.
  3. Change the binding to be used as webHttpBinding type.
So let's start by adding the WebGet attribute on the method. To use these attributes, we need to add reference to System.ServiceModel.Web.

Add the WebGet attribute on the implementation of the service method.

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Net;
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Web.Http;

namespace SampleApplication
{
    public class RESTService : IRESTService
    {
        [WebGet]
        List<POCOClass> IRESTService.GetListData()
        {
            var _lstPOCOClass = new List<POCOClass>();

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 1,
                Name = "User 1"
            });

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 2,
                Name = "User 2"
            });

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 3,
                Name = "User 3"
            }); 

            return _lstPOCOClass;
        }
    }
}

Next, in order to make it as a resource on the web, we use the UriTemplate parameter to the WebGet attribute above. We also add a parameter named ResponseFormat, to make it return a JSON type.
Code:
 [WebGet(UriTemplate = "/GetListData", ResponseFormat = WebMessageFormat.Json)]
        List<POCOClass> IRESTService.GetListData()
        {
            var _lstPOCOClass = new List<POCOClass>();

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 1,
                Name = "User 1"
            });

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 2,
                Name = "User 2"
            });

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 3,
                Name = "User 3"
            }); 

            return _lstPOCOClass;
        }
Now we need to add settings for making it use webHttpBinding.
First,  we need change the endpoint behavior to use the webHttpBinding. This is to be done inside
system.serviceModel => behaviors => endpointBehaviors => behavior
and change the endpoint to use the webHttpBinding. This is to be done in:
system.serviceModel => services => service => endpoint
The complete settings will look like:
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="SampleApplication.RESTService">
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
                  contract="SampleApplication.IRESTService" >
        </endpoint>
      </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

</configuration>
That's it. We are done with the settings and now we simply need to test it. To do this, we will browse the service to get the url.

Next, we use the Google chrome extension app called Postman to test the service. Add the service url and select GET as the HTTP verb.

Click the Send button and see the results.

Next, let's try to POST some data to it. So we add another method which receives data of the type POCOClass from the HttpBody. We also add the WebInvoke attribute and the UriTemplate for it.
 [WebInvoke(UriTemplate="/PostUserData", RequestFormat=WebMessageFormat.Json)]
        void IRESTService.PostUserData([FromBody] POCOClass userData)
        {

        }

Now again, we use our POSTMan app to POST the data to the same url, but with method name as per defined in the uri template.


Click Send and see the results. We are getting the results on the server.

Easy, isn't it. So create the REST services as per the requirements. No need to use the SOAP based WCF service, making it lighter.

No comments:

Post a Comment