Click here to Skip to main content
15,880,796 members
Articles / Web Development / ASP.NET
Tip/Trick

Configure WCF Service to REST

Rate me:
Please Sign up or sign in to vote.
3.85/5 (22 votes)
31 Oct 2014CPOL4 min read 64.2K   17   11
This tip explains how to write RESTFUL WCF service for Android applications.

Introduction

In this tip, I will try to explain about writing and configuring RESTFUL WCF services for Android applications.

Background

Basically, I do not know Android programming. Few days ago, I got a task to build an Android application for an already developed Complex CRM kind of application. It has so many functionalities like fire mail sending SMS at various stages which is built on MVC ASP.NET.

At that stage, we thought of coding every functionality in Android programming and there we don't know how much effort it will take to build fuctionalities like sending a mail, sending SMS and also we worried about the size of Android app if we insert all the code. So finally, we wondered how it would be if we reuse the code which is already in C# and we thought of using RESTFUL WCF services to communicate with the Android programming using JSON. So now, it's time to explain about how to write a WCF service for Android communication and also about WCF configuration.

Using the Code

Create a new WCF project as File ->New project -> WCF -> WCF Service Application. Now VS has created Service1.svc, IService1.cs, web.config files, etc. Now run the project. You can observe that the project is running in a WCF Test client. But my requirement as for the Android application is it should support for REST protocol using the HTTP.

Now, I will take a simple scenario where I need to build an Android app to insert a product and list all the products.

Configuration

Let us configure our web.config file as per our requirements.

Change the following code in your web.config section of your project.

XML
<system.serviceModel>
  <services>
    <service name="AndroidWCF.Service1" behaviorConfiguration="ServiceBehaviour">
      <!-- Service Endpoints -->
      <endpoint address="" binding="webHttpBinding"
      behaviorConfiguration="webBehavior" contract="AndroidWCF.IService1">
        <!--<identity>
          <dns value="localhost"/>
        </identity>-->

      </endpoint>

      <!--<endpoint address="mex"
      binding="mexHttpBinding" contract="IMetadataExchange"/>-->
    </service>

  </services>

  <behaviors>
    <serviceBehaviors>
      <behavior name="ServiceBehaviour">
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="webBehavior">
        <webHttp />
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
  </protocolMapping>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
  multipleSiteBindingsEnabled="true" />
</system.serviceModel>

Please find the detailed explanation of the configuration from the below steps.

Step 1

I have added the above part of the code under the <system.serviceModel> section of the web, and this code helps to configure and register the service and the contract.

XML
<services>
    <service name="AndroidWCF.Service1"
    behaviorConfiguration="ServiceBehaviour">
      <!-- Service Endpoints -->
      <endpoint address="" binding="webHttpBinding"
      behaviorConfiguration="webBehavior" contract="AndroidWCF.IService1">
        <!--<identity>
          <dns value="localhost"/>
        </identity>-->

      </endpoint>

      <!--<endpoint address="mex"
      binding="mexHttpBinding" contract="IMetadataExchange"/>-->
    </service>

  </services>

Step 2

Replace the code under <behaviors> section of the web.config file with the below code:

XML
<serviceBehaviors>
       <behavior name="ServiceBehaviour">
         <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
     <endpointBehaviors>
       <behavior name="webBehavior">
         <webHttp />
       </behavior>
     </endpointBehaviors>

In step 1, we have registered...

XML
behaviorConfiguration="ServiceBehaviour"

...so that I defined in step 2 and similarly for the endpointBehaviors.

So this is all about configuring the WCF service that supports RESTFUL services. Now my service is ready to work with RESTFUL service.

Now, I will build a small project that accepts input of type Project object and returns a list of Product object to demonstrate both GET and POST REST methods.

Step 1

Create a Product Class in your project.

XML
public class Product
  {
      public int ProductId { get; set; }
      public string ProductName { get; set; }
      public string ProductDescription { get; set; }
  }

Step 2

Create a service method as GetProducts() in Service1.svc.

C#
public List<Product> GetProducts()
      {
          List<Product> lst = new List<Product> {
              new Product { ProductId = 1,
              ProductName = "T-Shirt",
              ProductDescription = "Medium size"                 },
              new Product { ProductId = 2, ProductName = "Hero Honda",
              ProductDescription = "Very good vehicle" },
              new Product { ProductId = 3, ProductName = "Mobile",
              ProductDescription = "about mobile"                   }
          };
          return lst;
      }

Here, I have hardcoded the list instead of getting Product data from the database to make it simple.

Step 3

Add a method GetProducts() in IService1.cs:

C#
       [OperationContract]
       [WebGet(UriTemplate = "/GetProducts",
ResponseFormat = WebMessageFormat.Json,
 BodyStyle = WebMessageBodyStyle.Wrapped)]
       List<Product> GetProducts();

In the above method, you can see that there are two attributes added to the methods.

  1. [OperationContract]: attribute to register the GetProduct() method as a operation.
  2. [WebGet]: WebGet attribute is accepting UriTemplate as input used to name the method we can access from the browser. It may not be the same as the method name, ResponseFormat is used to configure the return format of the method, we can configure this either JSON or XML, WebGET is used by default for GET types of methods.

Everything is done. Now, run your service in browser (http://localhost:52404/Service1.svc/GetProducts) and call the service method GetProduct. You can see the output below:

Image 1

Now your Android programming can consume the above URL and can format the data and display it on your Android phone.

The above method demonstrated GET method that returns a JSON to the client.

Now, I will try for POST method that accepts the input of type Product and stores the data to the database.

Step 4

Create a service method as AddProduct() in Service1.svc.

C#
public string AddProduct(string productId,string ProductName,string ProductDescription)
     {
         // Save data to the database use the product object
         return "Saved";
     }

The above method accepts three inputs productId, ProductName and ProductDescription and we can save the details into the database.

Step 5

Add a method AddProduct() in IService1.cs:

C#
[OperationContract]
       [WebInvoke(Method = "POST",
       UriTemplate = "AddProduct/{productId}/{ProductName}/{ProductDescription}")]
       string AddProduct(string productId,string ProductName,string ProductDescription);

Here, I have used [WebInvoke] attribute which is the same as WebGet attribute but with this attribute we can customize the GET and POST type of method.

Now, you can use the above method in your Android programming to push the data to the service to insert data to the database.

Now, it's time to end this tip. You can ping me if you have any queries and suggestions. The comments section is open. Thanks for reading.

License

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


Written By
Software Developer TWB BANGALORE
India India
I Started my Programming career with C#.Currently using C#, ASP.NET, WCF, AJAX, & ASP.NET MVC to create Information Systems.

My interests involves Programming, C# is the best programming language and I love working with C# and other Microsoft Technologies.

Comments and Discussions

 
QuestionHow about passing a user-defined type as argument to the service Pin
TGabrielMbuy8-Apr-17 6:18
TGabrielMbuy8-Apr-17 6:18 
Questionpost send data Pin
x_jhofran_x17-Nov-14 5:35
x_jhofran_x17-Nov-14 5:35 
GeneralMy vote of 1 Pin
maq_rohit10-Nov-14 12:02
professionalmaq_rohit10-Nov-14 12:02 
GeneralMy vote of 1 Pin
priti@cp6-Nov-14 20:08
professionalpriti@cp6-Nov-14 20:08 
GeneralMy vote of 1 Pin
JasmineTheDev5-Nov-14 4:02
professionalJasmineTheDev5-Nov-14 4:02 
QuestionNicely explained Pin
G Ajit Kumar4-Nov-14 17:25
G Ajit Kumar4-Nov-14 17:25 
QuestionAn alternative example of setting up a WCF Service for iPhone, Android, or web apps... Pin
Michael Gledhill4-Nov-14 8:54
Michael Gledhill4-Nov-14 8:54 
GeneralMy vote of 4 Pin
saxenaabhi62-Nov-14 18:18
saxenaabhi62-Nov-14 18:18 
GeneralRe: My vote of 4 Pin
Shivarajbk3-Nov-14 17:25
Shivarajbk3-Nov-14 17:25 
GeneralMy vote of 1 PinPopular
Member 110841892-Nov-14 16:26
professionalMember 110841892-Nov-14 16:26 
GeneralMy vote of 1 PinPopular
dr.samuel.john1-Nov-14 10:46
dr.samuel.john1-Nov-14 10:46 

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.