MVC 4 WEB API .NET 4.5

Introduction

 
We can expose a Web API from ASP.NET MVC4. It is a new feature from Microsoft. Clients can get data from a Web API in any format such as JSON, XML, JSONP, HTML and etc.
 
I have already written about the Web API based methods in the http://www.c-sharpcorner.com/Blogs/9470/mvc4-web-api-that-supports-crud-operations-part-1.aspx blog.
 
Now in this article, I am going to explain how to create a new Web API application and how to get data in various formats such as I mentioned above.
 
Purpose
 
HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.
 
The ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. In this tutorial, you will use the ASP.NET Web API to create a web API that returns a list of products.
 
The following are the steps to create a new Web API application in Visual Studio 2011.
 
Step 1: We will create a new project and the project type will be MVC4. See the following image:
 
Step 2: Now we will select a Web API template from the Project template Dialog window.
 
WebApi2.png
 
Step 3: Now we will create a Customer controller inside the Controller folder and will select an API controller with read/write actions.
 
Step 4: Now we will add an Entity Data Model for our Database where we have a Customer Table. You can see it in the attached Source code.
 
Step 5: It's time to modify our CustomerController to fetch and save data. See the code below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6. using WEBAPISample45.Models;  
  7.   
  8. namespace WEBAPISample45.Controllers {  
  9.         public class CustomerController: ApiController {  
  10.             private CompanyDBEntities context = new CompanyDBEntities();  
  11.             // GET /api/customer  
  12.             public IEnumerable < CustomerModel > Get() {  
  13.                 IEnumerable < CustomerModel > list = null;  
  14.                 list = (from c in context.Customers select new CustomerModel { Id = c.Id, Name = c.Name, Salary = (long) c.Salary }  
  15.                     .AsEnumerable < CustomerModel > ();  
  16.                     return list;  
  17.                 }  
  18.                 // GET /api/customer/5  
  19.                 public CustomerModel Get(int id) {  
  20.                     return (from c in context.Customers where c.Id == id select new CustomerModel {  
  21.                         Id = c.Id,  
  22.                             Name = c.Name,  
  23.                             Salary = (long) c.Salary  
  24.                     }).FirstOrDefault < CustomerModel > ();  
  25.                 }  
  26.                 // POST /api/customer  
  27.                 public void Post(CustomerModel customer) {  
  28.                     context.AddToCustomers(new Customer {  
  29.                         Id = customer.Id, Name = customer.Name, Salary =  
  30.                             customer.Salary  
  31.                     });  
  32.                     context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);  
  33.                 }  
  34.                 // PUT /api/customer/5  
  35.                 public void Put(int id, CustomerModel customer) {  
  36.                     var cust = context.Customers.First(c => c.Id == id);  
  37.                     cust.Name = customer.Name;  
  38.                     cust.Salary = customer.Salary;  
  39.                     context.SaveChanges();  
  40.                 }  
  41.                 // DELETE /api/customer/5  
  42.                 public void Delete(int id) {  
  43.                     var cust = context.Customers.First(c => c.Id == id);  
  44.                     context.Customers.DeleteObject(cust);  
  45.                     context.SaveChanges();  
  46.                 }  
  47.             }  
  48.         } 
Step 6: Now the most important thing is that in the global.asax, MapHttpRoute should be registered. See the highlighted code below:
  1. public static void RegisterRoutes(RouteCollection routes) {  
  2.   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  3.   routes.MapHttpRoute(  
  4.       name: "DefaultApi",  
  5.       routeTemplate: "api/{controller}/{id}",  
  6.       defaults: new { id = RouteParameter.Optional }  
  7.   );  
  8.   routes.MapRoute(  
  9.       name: "Default",  
  10.       url: "{controller}/{action}/{id}",  
  11.       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  12.   );  
Step 7: Now we will run our application and see the output of the web API. Applications will run on the local server http://localhost:40683/ and you have to add the api/customer to the URL. So now your URL will be http://localhost:40683/api/customer.  
 
If you want to access a customer by id then you can use http://localhost:40683/api/customer/1 as the URL.
 
Now I am going to discuss a very important thing here. In the Web API, whatever format we use to send a request is the format of the returned response.
 
In the following JavaScript code, we are requesting data in JSON format. So the response will be returned in the JSON format. I will explain via Fiddler.
 
JSON
  1. <script type="text/javascript">  
  2.     $(document).ready(function () {  
  3.         $.ajax({  
  4.   
  5.             type: "GET",  
  6.             url: "api/customer/1",  
  7.             dataType: "json",  
  8.             success: function (data) {  
  9.                      alert(data);  
  10.             }  
  11.         });  
  12.     });  
  13. </script> 
XML
  1. <script type="text/javascript">  
  2.     $(document).ready(function () {  
  3.         $.ajax({  
  4.   
  5.             type: "GET",  
  6.             url: "api/customer/1",  
  7.             dataType: "xml",  
  8.             success: function (data) {  
  9.                      alert(data);  
  10.             }  
  11.         });  
  12.     });  
  13. </script> 
HTML
  1. <script type="text/javascript">  
  2.     $(document).ready(function () {  
  3.         $.ajax({  
  4.   
  5.             type: "GET",  
  6.             url: "api/customer/1",  
  7.             dataType: "html",  
  8.             success: function (data) {  
  9.                      alert(data);  
  10.             }  
  11.         });  
  12.     });  
  13. </script> 
If you see the above jQuery code we are only changing the DataType and we are not changing anything inside the Web API.
 
Now we will open Fiddler and see how we can get data in various formats.
 
Open Fiddler and go to the Composer tab. See the following screen:
 
In the above image, you will see the "Accept: text/html, text/html, */*; q=0.01" when we execute the query it will return a response in HTML format.
 
Now we will change the datatype to XML "Accept: application/xml, text/xml, */*; q=0.01"
 
and will see the output in XML format.
 
WebApi9.png
 
Now we will change the datatype to JSON "Accept: application/json, text/javascript, */*; q=0.01" 
 
 
And the output is in JSON format:
 
 
References 
 
Happy coding.