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.