In this post we will see how to create a our own WEB API service and will consume it in client using JQuery.
This is the UI i am planning to create, which in-turn talk to a ASP.NET WEB API Service for rendering data. We need to create a API Service and an Application consuming it.
Lets do it step by step.
Step 1: Create a solution and add 2 MVC 4 projects , one with WEB API template and another with INTERNET Application template.
Step 2: Lets create our custom WEB API Service. Go to API_SVC project and under Controllers folder you can see ValuesController.cs. This is the default WEB API service fie added, either you can modify, or you can add a new API Controller, using Add option.
Step 3:I created a Service file with name "EmployeeAPI".
EmployeeAPIConstroller.cs
namespace API_SVC.Controllers { public classEmployeeAPI Controller : ApiController { private ListEmpList = new List (); public EmployeeAPIController() { EmpList.Add(new Employee(1, "Employee1", "Employee Department1", 9999888877)); EmpList.Add(new Employee(2, "Employee2", "Employee Department2", 7777888899)); EmpList.Add(new Employee(3, "Employee3", "Employee Department3", 9999777788)); } // GET api/EmployeeAPI public IEnumerable<Employee>GetEmployees () { return EmpList; }// GET api/EmployeeAPI/5 public EmployeeGetEmployee (int id) { return EmpList.Find(e => e.ID == id); }// POST api/EmployeeAPI public IEnumerable<Employee>Post (Employee value) { EmpList.Add(value); return EmpList; }// PUT api/EmployeeAPI/5 public voidPut (int id, string value) { }// DELETE api/EmployeeAPI/5 public IEnumerable<Employee>Delete (int id) { EmpList.Remove(EmpList.Find(E => E.ID == id)); return EmpList; } } }
Step 4:I ensure that it is hosted on IIS and can be accessed through URL mentioned on each of the service methods. for example lets check GetEmployee() method using Fiddler.
Action:
Result:
Now that we confirm that we are done with creation of simple WEB API HTTP Service.
Step 5: Move to the second application i.e., API_APP , the MVC 4 internet application, and open Index.cshtml under Home. To demonstrate the simplicity of ASP.NET WEB API Service, i will call them using nothing but JQuery i.e., Client side code.
Index.cshtml Code View:
@{ ViewBag.Title = "Home Page"; } @section featured { <section class="featured"> <div class="content-wrapper"> <hgroup class="title"> <h1>@ViewBag.Title.</h1> <h2>@ViewBag.Message</h2> </hgroup> <div> <table><tr> <td><buttonIndex.cshtml UI view:onclick="GetAllEmployees();return false;" >Get All Employees</button></td> <td>Enter Employee Id: <input type="text" id="txtEmpid" style="width:50PX"/></td> <td><buttononclick="GetEmployee();return false;" >Get Employee</button></td> <td> <table> <tr><td>EmpId:</td><td><input type="text" id="txtaddEmpid" /></td></tr> <tr> <td>Emp Name:</td><td><input type="text" id="txtaddEmpName" /></td></tr> <tr> <td>Emp Department:</td><td><input type="text" id="txtaddEmpDep" /></td></tr> <tr><td>Mobile no:</td><td><input type="text" id="txtaddEmpMob" /></td></tr> </table> </td> <td><buttononclick="AddEmployee();return false;" >Add Employee</button></td> <td>Delete Employee <input type="text" id="txtdelEmpId" style="width:50PX"/></td> <td><buttononclick="DeleteEmployee(); return false;" >Delete Employee</button></td> </tr></table> </div> </div> </section> } <h3>Oputput of action done through WEB API:</h3> <ol class="round"> <li> <div id="divResult"></div> </li> </ol>
Step 6: Lets see how we can associate each button to an action of API Service. First look at "Get All Employees" button and its onclick event in above code.Its is calling "GetAllEmployees()" , a script function in-turn calling WEB API Service using JQuery.
functionSpare sometime looking at above code snippet.GetAllEmployees () { jQuery.support.cors = true; $.ajax({ url:'http://localhost:8080/API_SVC/api/EmployeeAPI' , type:'GET' , dataType: 'json', success: function (data) {WriteResponse (data); }, error: function (x, y, z) { alert(x + '\n' + y + '\n' + z); } }); }
Step 7: WriteResponse() and ShowEmployee() are the 2 methods i created to display the JSON result in a proper way. Below is the JQuery part associating each button to a method of WEB API Service.
<script type="text/javascript"> functionStep 8: What else we left with except verifying the output.GetAllEmployees () { jQuery.support.cors = true; $.ajax({ url: 'http://localhost:8080/API_SVC/api/EmployeeAPI', type: 'GET', dataType: 'json', success: function (data) { WriteResponse(data); }, error: function (x, y, z) { alert(x + '\n' + y + '\n' + z); } }); } functionAddEmployee () { jQuery.support.cors = true; var employee = { ID: $('#txtaddEmpid').val(), EmpName: $('#txtaddEmpName').val(), EmpDepartment: $('#txtaddEmpDep').val(), EmpMobile: $('#txtaddEmpMob').val() }; $.ajax({ url: 'http://localhost:8080/API_SVC/api/EmployeeAPI', type: 'POST', data:JSON.stringify(employee), contentType: "application/json;charset=utf-8", success: function (data) { WriteResponse(data); }, error: function (x, y, z) { alert(x + '\n' + y + '\n' + z); } }); } functionDeleteEmployee () { jQuery.support.cors = true; var id = $('#txtdelEmpId').val() $.ajax({ url: 'http://localhost:8080/API_SVC/api/EmployeeAPI/'+id, type: 'DELETE', contentType: "application/json;charset=utf-8", success: function (data) { WriteResponse(data); }, error: function (x, y, z) { alert(x + '\n' + y + '\n' + z); } }); } functionWriteResponse (employees) { var strResult = "<table><th>EmpID</th><th>Emp Name</th><th>Emp Department</th><th>Mobile No</th>"; $.each(employees, function (index, employee) { strResult += "<tr><td>" + employee.ID + "</td><td> " + employee.EmpName + "</td><td>" + employee.EmpDepartment + "</td><td>" + employee.EmpMobile + "</td></tr>"; }); strResult += "</table>"; $("#divResult").html(strResult); } functionShowEmployee (employee) { if (employee != null) { var strResult = "<table><th>EmpID</th><th>Emp Name</th><th>Emp Department</th><th>Mobile No</th>"; strResult += "<tr><td>" + employee.ID + "</td><td> " + employee.EmpName + "</td><td>" + employee.EmpDepartment + "</td><td>" + employee.EmpMobile + "</td></tr>"; strResult += "</table>"; $("#divResult").html(strResult); } else { $("#divResult").html("No Results To Display"); } } functionGetEmployee () { jQuery.support.cors = true; var id = $('#txtEmpid').val(); $.ajax({ url: 'http://localhost:8080/API_SVC/api/EmployeeAPI/'+id, type: 'GET', dataType: 'json', success: function (data) { ShowEmployee(data); }, error: function (x, y, z) { alert(x + '\n' + y + '\n' + z); } }); } </script>
Action 1:
Action 2:
Action 3:
Action 4:
Step 9: Apart from fact that it is simple to configure and create, we need to consider that its a RESTful service which is light weight and will have incredible performance.
Look at the below snapshot of HttpWatch Log for Action #1, which was completed in
With this we have seen how to
Download Code:Can any service configuration be simpler than this?
Search for api_sln.zip here.
Note: Removed additional folder names "package" to reduce overload of upload. When download, try create a new project and the Package folder with required dlls will be created by VS 2012 RC. Copy that package folder to working folder of this solution and then execute it.
Is it helpful for you? Kindly let me know your comments / Questions.
Hi Pratap
ReplyDeletei write your article Implementing & Consuming ASP.NET WEB API from JQuery (MVC 4) but i'm not understanding how to host this on iis. Due to this i'm unable to compile my code. pl give a solution
Rohit, If you install VS2012 RC, by defalut it will install iis express, so just go to Properties of project and go to WEB tab, and select IIS hosting instead of visual studio and hit Create Virtual directory button. You are good to go....
Delete:)
Hi,
ReplyDeletei make a service & host this on iis but when i run it on fiddler then it show the error page not found which like be http 404 error
url of service is: http://localhost:30106/WebAPI/api/EmployeeAPI
Rohit
Deletethat depends on how you use Fiddler. there is a post on MS on it. Please follow it. else send me a snapshot of the screen via mail, so that we can point out the mistake.
Pl tell how to download Implementing & Consuming ASP.NET WEB API from JQuery (MVC 4)
ReplyDeleteChanged the link for source code.
DeleteHow can I download the code? Thanks, jabits
ReplyDeleteChanged the link for source code.
DeleteNice job. Like your use of error functions on the ajax call.
ReplyDeleteWhy are you using MVC to host your api controllers? Why did you not just create a class library for your apicontroller's so you can nunit them and host them in your host mvc application? Seems like a lot of overhead to maintain all of those configuration files, etc.
ReplyDeleteHi Eric
DeleteI got your point, and i agree with you that the API should be part of a separate class library. But the moto here is to demonstrate the sample with simplest possible way without design botheration. :)
Awesome - thank you for the time you took to do this. I know many people will find this post very useful. Cheers mate.
DeleteI'm not able to download your code. See below
ReplyDeleteYou (account name 'rgr97') have just tried to access a document in another KeepandShare account 'ppreddy1983'. To view it you need to ask the owner of the other account to set the Sharing controls to give your KeepandShare user name 'rgr97' rights to view the document.
Changed the link for source code.
Delete