Click here to Skip to main content
15,867,686 members
Articles / Web Development / HTML
Tip/Trick

How to Create WCF REST Service for Mobile App

Rate me:
Please Sign up or sign in to vote.
4.61/5 (9 votes)
18 Mar 2015CPOL3 min read 27.8K   349   26   10
This tip will show you how to create a WCF service return JSON use for mobile app.

Introduction

In the era of smartphones and cloud throne, mobile applications now require not only beautiful interface and good quality, but also the ability to synchronize data between devices using server side technologies. If you have plans to build applications like social apps, financial apps… you should care about technologies helping in building data service as soon as possible.

Currently, there are lots of technologies in .NET Framework that help you in building service, but in this tip, we will go into detail about the steps to create WCF REST Service that can be used on the mobile app or other client as desktop app, web app.

Background

JSON (JavaScript Object Notation) is a lightweight, language independent, data-interchange format. JSON is a syntax for storing and exchanging text information. JSON is smaller than XML, faster and easier to parse.

REST: "Representational State Transfer, attempts to codify the architectural style and design constraints that make the Web what it is. REST emphasizes things like separation of concerns and layers, statelessness, and caching, which are common in many distributed architectures because of the benefits they provide. These benefits include interoperability, independent evolution, interception, improved scalability, efficiency, and overall performance."

Using the Code

I) Create WCF REST Service

In the first part, we will create a WCF service that returns data in JSON format in 5 steps detailed below:

  1. In Visual Studio 2013, we create a new web project.

    Image 1

  2. Then, add a new item to the project and select WCF Service Item.

    Image 2

    Image 3

  3. Delete the default generated code by Visual Studio and add two methods, PostMessage and GetMessage as below:
    C#
    namespace Tungnt.NET.WCFRestDemo
    {
        [ServiceContract]
        public interface IWCFRestDemo
        {
            [OperationContract]
            string GetMessage();
     
            [OperationContract]
            string PostMessage(string userName);
        }
    }
  4. To use the WCF service as REST return JSON data, we need to change service interface’s methods as attributes use WebGet (GET data only) or WebInvoke (for GET/POST/PUT/DELETE data) like below. (Note: These attributes are members of System.ServiceModel.Web.dll so we need to add this reference before use.)

    Image 4

    Image 5

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
     
    namespace Tungnt.NET.WCFRestDemo
    {
        [ServiceContract]
        public interface IWCFRestDemo
        {
            [OperationContract]
            [WebGet(RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
            //Same as [WebInvoke(Method="GET", RequestFormat = WebMessageFormat.Json, 
            //ResponseFormat = WebMessageFormat.Json)]
            string GetMessage();
     
            [OperationContract]
            [WebInvoke(Method="POST", 
            RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
            string PostMessage(string userName);
        }
    }
  5. In the final step, we will implement the interface’s functions GetMessage/PostMessage as below:
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
     
    namespace Tungnt.NET.WCFRestDemo
    {
        public class WCFRestDemo : IWCFRestDemo
        {
            public string GetMessage()
            {
                return "Welcome to tungnt.net from GetMessage() WCF REST Service";
            }
     
            public string PostMessage(string userName)
            {
                return string.Format("Welcome {0} to tungnt.net 
                          from PostMessage() WCF REST Service", userName);
            }
        }
    }

II) Configure WCF REST Service

We’ve just created WFC REST service but to use this service on mobile app, we need one more step: Configuration service to return JSON format instead of the default format SOAP (XML). In this second part, we will configure WCF to use webHttpBinding to enable WCF service returns JSON format. Let’s edit the web.config as follows:

Add an endpoint used webHttpBinding and restBehavior (helpEnabled = true to serve the development process as will be mentioned below):

XML
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="restBehavior">
        <webHttp helpEnabled="true"/>
      </behavior>
    </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
      <service name="Tungnt.NET.WCFRestDemo.WCFRestDemo">
        <endpoint name ="RESTEndPoint" contract ="Tungnt.NET.WCFRestDemo.IWCFRestDemo" 
        binding ="webHttpBinding" 
        address ="rest" behaviorConfiguration ="restBehavior"/>
      </service>
    </services>
  </system.serviceModel>

WCF REST service is ready to use, let's check WCF REST service can be used or not right now. Right click on the WCFRestDemo.svc file and select View In Browser.

Image 6

Add rest at the end of the browser’s URL as configured in web.config endpoint address and hit enter. You will see the results as shown below:

Image 7

Click service help page (as configured helpEnabled = true in web.config above) to see the rest of the methods in this service.

Image 8

Successfully, we have just created and configured WCF REST Service that can be used in web app or mobile app.

Points of Interest

In this tip, I showed you how to create WCF REST service returns JSON data to be used in web applications (via JavaScript) or mobile applications such as iOS, Android, Windows Phone app… JSON is a format that is very popular today in the world of Web/Mobile because of the simplicity, lightweight and high portability so understanding how to use it has become a strong demand knowledge for developer. Hopefully, this tip will be helpful for you in the process of building your own applications. In the following post, we will learn how to use this service on the Web, Windows Phone, Windows App … The detail article please read on the link below:

If you have any questions or any experiences or ideas, please share in the comments below.

History

  • 18th March, 2015: Initial post

License

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


Written By
Architect MISA JSC
Vietnam Vietnam
I'm a chief software architect at MISA JSC a software vendor from Ha Noi, Viet Nam, mostly working with Microsoft technologies, especially is Silverlight, Entity Framework, ASP.NET and more. I hold a BS degree in Computer Science obtained from VietNam National University, Ha Noi.
My hobbies are playing Badminton and listen to music in free time.

If you like my article, please visit my blog for more: http://tungnt.net

Comments and Discussions

 
GeneralNice Tip Pin
Mathi Mani24-Mar-15 7:22
Mathi Mani24-Mar-15 7:22 
GeneralRe: Nice Tip Pin
tungnt18524-Mar-15 7:59
tungnt18524-Mar-15 7:59 
QuestionRest Service for text/xml Pin
Bon-Ton19-Mar-15 16:36
Bon-Ton19-Mar-15 16:36 
AnswerRe: Rest Service for text/xml Pin
tungnt18519-Mar-15 18:09
tungnt18519-Mar-15 18:09 
Hi Bon-Ton,

JSON is lightweight than XML so I curious why do you want to use it.
In your case you can configure service to add one endpoint for xml besides the one for REST.

Regards.
GeneralRe: Rest Service for text/xml Pin
Bon-Ton20-Mar-15 6:38
Bon-Ton20-Mar-15 6:38 
GeneralRe: Rest Service for text/xml Pin
tungnt18521-Mar-15 2:18
tungnt18521-Mar-15 2:18 
Suggestionnext one Pin
eXplodus18-Mar-15 22:19
eXplodus18-Mar-15 22:19 
GeneralRe: next one Pin
tungnt18518-Mar-15 22:35
tungnt18518-Mar-15 22:35 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun18-Mar-15 19:56
Humayun Kabir Mamun18-Mar-15 19:56 
GeneralRe: My vote of 5 Pin
tungnt18518-Mar-15 20:17
tungnt18518-Mar-15 20:17 

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.