Click here to Skip to main content
15,879,474 members
Articles / WebAPI
Tip/Trick

Comparison between RESTFUL Service without SVC file and Web API with a simple example

Rate me:
Please Sign up or sign in to vote.
4.67/5 (4 votes)
27 Aug 2014CPOL2 min read 13K   5   3
Comparison between Restful Service and Web API with a simple example

Introduction

In this Article we will see how to create a RESTFUL service without SVC file and a WebAPI to return a simple JSON data and get data from Service and Web API using JQuery.

Using the code

First Let us first create a simple RESTFul Service to get country List. 

1.  Open Visual studio 2012
2.  Open File -> New Project -> Visual C# ->WCF-> WCF Service Application
3.  Give Service Name as 'RESTService'.
4.  Once solution is open, delete ‘Service1.svc’ and ‘IService1.cs’ files from the solution
5.  Add reference ‘System.ServiceModel.Activation.dll’. This DLL will be oftern in C:\Program        Files\ReferenceAssemblies\Microsoft\Framework\.NETFramework\v4.0\System.ServiceModel.Activation.dll
6.   Add two class files ‘GetData.cs’ and ‘IGetData.cs’ to the Project
7.   Add global.asax file to our project and configure our Root. Our gloabl.asax file will look like below

using System;
using System.ServiceModel.Activation;
using System.Web.Routing;

namespace RESTService
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.Add(new ServiceRoute("RESTService", new WebServiceHostFactory(), typeof(GetData)));
        }

    }
}

Note:  Here 'RESTService' is the name of our name. 

8. Add a class Called 'CountryList.cs' to the Project and add two Properties as shown below

public class CountryList
    {
        public string CountryCode { get; set; }
        public string CountryName { get; set; }
    }

9. Add an Interface 'IGetData' to 'IGetData.cs' and Add Method 'GetCountryList' in the interface

using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace RESTService
{
    [ServiceContract]
    interface IGetData
    {
        [OperationContract]
        [WebInvoke(Method="GET",UriTemplate = "GetCountryList", ResponseFormat = WebMessageFormat.Json)]
        IEnumerable<CountryList> GetCountryList();

    }
}

10. Add Method 'GetCountryList' in our GetData.cs file and inherit the class from IGetData interface

using System;
using System.IO;
using System.Collections.Generic;  
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace RESTService
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class GetData : IGetData
    {
     
        public IEnumerable<CountryList> GetCountryList()
        {
            CountryList objCountry;
            List<CountryList> Country = new List<CountryList>();
            objCountry = new CountryList();
            objCountry.CountryCode = "IN";
            objCountry.CountryName = "India";
            Country.Add(objCountry);
            objCountry = new CountryList();
            objCountry.CountryCode = "US";
            objCountry.CountryName = "United States";
            Country.Add(objCountry);
            return Country;
        }
    }

Note:  In the above code we are returning Country list which contain contry code and country name.

11. Now we need to modify our web.config file as shown below.

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation targetFramework="4.0" debug="true"/>
    <customErrors mode ="Off"> </customErrors>
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
   </system.serviceModel>
</configuration>

Build our application. Our service is ready.

Now we will try to invoke our service using JQuery. For that we will create a simple HTML page as shown below. In the HTML page we are refering 'jquery-1.7.1.min.js'.

<html>
 <head>
    <script src="/jquery-1.7.1.min.js"></script>
    <script type="text/javascript">
        function GetRestData() {
            $.support.cors = true;
            $.ajax({
                type: "GET",
                url: "http://localhost:60112/RestService/GetCountryList",
                dataType: "json",
                success: function (data) {
                    $("#divCountryList").empty();
                    var ctable = ("<table border='1'>");
                    for (var i = 0; i < data.length; i++) {
                        ctable += "<tr><td>"+ data[i].CountryCode+ "</td><td>"+ data[i].CountryName+"</td></tr>";
                    }
                    ctable +="</table>";
                    $('#divCountryList').html(ctable);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus + "," + errorThrown.toString());
                }

            });
        }

    </script>
</head>
<body>
    <input type="submit" id="btnOne"  value="Invoke Restful Data" onclick="GetRestData(); return false;"  />
        <div id="divCountryList"></div>
</body>
</html

 Note: In the above code we are calling 'GetCountryList' method of RESTFul service and creating an html table to display the result. 

Now Letus try to Achive same task using a WebAPI.

1.  Open Visual studio 2012
2.  Open File -> New Project -> Visual C# ->ASP.NET MVC 4 Web Application. Give our application name as SimpleWebAPI
3.  In the Next window select 'Web API' and select Razor as view engine as shown below.

4. Once our Web API  is loaded open ValuesController.cs file and delelete all methods from ValuesController class and add our same method GetCountryList. Now our ValuesController.cs will be looks as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SimpleWebAPI.Controllers
{
    public class ValuesController : ApiController
    {
        public IEnumerable<CountryList> GetCountryList()
        {
            CountryList objCountry;
            List<CountryList> Country = new List<CountryList>();
            objCountry = new CountryList();
            objCountry.CountryCode = "IN";
            objCountry.CountryName = "India";
            Country.Add(objCountry);

            objCountry = new CountryList();
            objCountry.CountryCode = "US";
            objCountry.CountryName = "United States";
            Country.Add(objCountry);
            return Country;
        }

        public class CountryList
        {
            public string CountryCode { get; set; }
            public string CountryName { get; set; }
        }
      
    }
}

5. Now build our Web API.

Now we will try to invoke our service using JQuery. For that we will create a simple HTML page as shown below. In the HTML page we are refering 'jquery-1.7.1.min.js'.

<html>
 <head>
    <script src="/jquery-1.7.1.min.js"></script>
    <script type="text/javascript">
        function GetWebAPIData() {
            $.support.cors = true;
            $.ajax({
                type: "GET",
                url: "http://localhost:62811/API/Values/GetCountryList",
                dataType: "json",
                success: function (data) {
                    $("#divCountryList").empty();
                    var ctable = ("<table border='1'>");
                    for (var i = 0; i < data.length; i++) {
                        ctable += "<tr><td>"+ data[i].CountryCode+ "</td><td>"+ data[i].CountryName+"</td></tr>";
                    }
                    ctable +="</table>";
                    $('#divCountryList').html(ctable);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus + "," + errorThrown.toString());
                }

            });
        }

    </script>
</head>
<body>
    <input type="submit" id="btnTwo"  value="Invoke Web API" onclick="GetWebAPIData(); return false;"  />
        <div id="divCountryList"></div>
</body>
</html

 Note: In the above code we are calling 'GetCountryList' method of Web API and creating an html table to display the result.

Points of Interest

In the above article we created a RESTFUL service and a Web API to perform same task and we consumed both using an HTML page with JQUery. 

License

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


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionGood article Pin
marcoingegneri31-Aug-14 22:01
professionalmarcoingegneri31-Aug-14 22:01 
GeneralRe: Good article Pin
Mahesh Nandanan31-Aug-14 22:57
Mahesh Nandanan31-Aug-14 22:57 
QuestionSuggestion Pin
aSarafian27-Aug-14 21:39
aSarafian27-Aug-14 21:39 
It would be nice to add the input and output of the request as it appears on the wire.

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.