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.
<system.serviceModel>
<services>
<service name="AndroidWCF.Service1" behaviorConfiguration="ServiceBehaviour">
-->
<endpoint address="" binding="webHttpBinding"
behaviorConfiguration="webBehavior" contract="AndroidWCF.IService1">
-->
</endpoint>
-->
</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.
<services>
<service name="AndroidWCF.Service1"
behaviorConfiguration="ServiceBehaviour">
-->
<endpoint address="" binding="webHttpBinding"
behaviorConfiguration="webBehavior" contract="AndroidWCF.IService1">
-->
</endpoint>
-->
</service>
</services>
Step 2
Replace the code under <behaviors>
section of the web.config file with the below code:
<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...
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.
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.
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:
[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.
[OperationContract]
: attribute to register the GetProduct()
method as a operation.
[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:
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.
public string AddProduct(string productId,string ProductName,string ProductDescription)
{
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:
[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.