Introduction To ASP.NET WebAPI And Return Result In Different Formats

Introduction

 
In this article, we will discuss Web API and its return types. Here is the agenda of this article:
  1. What is Web API.
  2. What are the advantages of Web API(against WCF).
  3. Demo Web API with CRUD operation.
  4. Send result in different formats like XML, Json. 

What is Web API

 
ASP.NET Web API is a framework which is used to make it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
 
Moreover Web API is open source and an ideal platform for building REST-ful services over the .NET framework. It uses HTTP methods mainly GET, POST, PUT, DELETE to communicate with client. Unlike WCF Rest service, it use the complete features of HTTP (like URIs, request/response headers, caching, versioning, various content formats) and you don't need to define any extra config settings for different devices unlike WCF Rest service.
 

We already have WCF, then why Web API?

 
If there is a requirement to develop a web service and it is not related to transaction, SOAP based, TCP, NamedPipe, MSMQ protocol and two-way communication (duplex) then Web API is best.
 
It doesn't have complex and tedious configuration in WCF REST service. It is only based on HTTP and easy to define, expose and consume in a REST-ful way. It is light weight architecture and good for latest devices which have limited bandwidth like smart phones, tablets etc. It is open source.
 
It has automatic support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition. It can be hosted within the application or on IIS.
 
It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection that makes it more simple and robust.
 

Web API Demo with CRUD operation

 
In this section, we will go through couple of steps how to create Web API and perform CRUD operation.
 
Step 1

Open Visual Studio - Go to File Menu, Select Add, then choose "New Project". After choosing new project the following(Figure1) popup box appears. It shows different types of projects like Web, Windows, Console or MVC, you need to choose "ASP.NET MVC 4 Web Application" .
 
 
Figure 1: Add New MVC project
 
Step 2

Once you choose MVC project, you need to select MVC project type. So, select Web API project.
 
 
Figure 2: Choose Web API project
 
Step 3(Model)

Add Blog class to Models folder. Blog class contains 3 properties Id, Name and Url.
 Before starting coding I want to discuss what we are going to do. Web API will contain blog information and client will send AJAX request to API to get information about blog.
  1. public class Blog  
  2. {  
  3.     public int Id { getset; }  
  4.     public string Name { getset; }  
  5.     public string Url { getset; }          
  6. }  
Step 4(Controller)

After adding Web API project, you need to add one controller. Just right click on Controllers folder and Add Controller (See figure 3).
 
 
Figure 3: Add New Controller
 
 
Figure 4: Choose proper template for Controller
 
Here BlogController class is inherited from ApiController. It contains methods Get() to get all records, Post() to add record, Get(int id) to search record, put() to update record and delete record. Those methods will be called from Client application through AJAX request. It is using a demo blogList(static variable) which contains couple of Blog Object but in real-life you will use EntityFramework or ADO.NET. Here is the complete code for controller:
  1. public class BlogController : ApiController  
  2. {  
  3.     public static List<Blog> blogList = new List<Blog>()  
  4.         {  
  5.             new Blog { Id = 1, Name="C-SharpCorner", Url="http://www.c-sharpcorner.com/"},  
  6.             new Blog { Id = 2, Name="CodeProject", Url="http://www.codeproject.com"},  
  7.             new Blog { Id = 3, Name="StackOverflow", Url="http://stackoverflow.com/"},  
  8.         };  
  9.   
  10.     // GET api/default1  
  11.     public List<Blog> Get()  
  12.     {  
  13.         return blogList;  
  14.     }  
  15.   
  16.     // GET api/blog/5  
  17.     public Blog Get(int id)  
  18.     {  
  19.         Blog blogObject = (from blog in blogList  
  20.                            where blog.Id == id  
  21.                            select blog).SingleOrDefault();  
  22.         return blogObject;  
  23.     }  
  24.   
  25.     // POST api/blog  
  26.     public List<Blog> Post(Blog blogObj)  
  27.     {  
  28.         blogList.Add(blogObj);  
  29.   
  30.         return blogList;  
  31.     }  
  32.   
  33.     // PUT api/blog/5  
  34.     public void Put(Blog blogObj)  
  35.     {  
  36.         Blog blogOrignalObject = (from blog in blogList  
  37.                                   where blog.Id == blogObj.Id  
  38.                                   select blog).SingleOrDefault();  
  39.   
  40.         blogOrignalObject.Name = blogObj.Name;  
  41.         blogOrignalObject.Url = blogObj.Url;  
  42.     }  
  43.   
  44.     // DELETE api/blog/5  
  45.     public void Delete(int id)  
  46.     {  
  47.         blogList.RemoveAll(temp => temp.Id == id);  
  48.     }  
  49. }  
Step 5(View)

We will design view page where we will call Web API and display data returns by API. Here we will perform CRUD  (Create, Read, Update, Delete) operations.
  1. <div>    
  2.     <h2>All Blogs</h2>    
  3.     <table border="1" cellpadding="0" cellspacing="0" id="blogs">    
  4.         <tr>    
  5.             <th>Id</th>    
  6.             <th>Name</th>    
  7.             <th>Url</th>    
  8.         </tr>    
  9.     </table>    
  10. </div>    
  11. <div>    
  12.     <h2>Search by ID</h2>    
  13.     <input type="text" id="blogId" size="5" />    
  14.     <input type="button" value="SearchBlog" onclick="find();" />    
  15.     <p id="blog" />    
  16.     
  17.     <h1>Add Blog</h1>    
  18.     Id:    
  19.     <input type="text" id="Id" /><br />    
  20.     Name:    
  21.     <input type="text" id="Name" /><br />    
  22.     Url:    
  23.     <input type="text" id="Url" /><br />    
  24.     <input type="button" value="AddBlog" onclick="add();" />    
  25. </div>  
Preceding code contains a table to display data, search record and add record. AJAX request will record to controls. Here is the complete code for AJAX request:
  1. <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>  
  2. <script>  
  3.     $(document).ready(function () {  
  4.   
  5.         // Send an AJAX request  
  6.         $.ajax({  
  7.             url: 'http://localhost:1312/api/Blog?type=json',  
  8.             type: "GET",  
  9.             data: {},  
  10.             dataType: "json",  
  11.             success: function (result) {  
  12.                 // On success, 'data' contains a list of products.  
  13.                 var htmlContent = "";  
  14.   
  15.                 $.each(result, function (key, item) {  
  16.                     htmlContent = htmlContent + "<tr><td>" + item.Id + "</td><td>" + item.Name + "</td><td>" + item.Url + "</td></tr>";  
  17.                 });  
  18.   
  19.                 // Appending HTML content  
  20.                 $('#blogs').append(htmlContent);  
  21.             },  
  22.             error: function (err) {  
  23.                 alert(err.statusText);  
  24.             }  
  25.         });  
  26.     });  
  27.     
  28.     // Adding Blog record
  29.     function add() {  
  30.         var Id = $('#Id').val();  
  31.         var Name = $('#Name').val();  
  32.         var Url = $('#Url').val();  
  33.         var blogData = { "Id": Id, "Name": Name, "Url": Url };  
  34.   
  35.         $.ajax({  
  36.             url: 'http://localhost:1312/api/Blog?type=json',  
  37.             type: "POST",  
  38.             contentType: "application/json",  
  39.             data: JSON.stringify(blogData),  
  40.             dataType: "json",  
  41.             success: function (result) {  
  42.                 // On success, 'data' contains a list of products.  
  43.                 var htmlContent = "";  
  44.   
  45.                 $("#blogs > tbody > tr").remove();  
  46.   
  47.                 $.each(result, function (key, item) {  
  48.                     htmlContent = htmlContent + "<tr><td>" + item.Id + "</td><td>" + item.Name + "</td><td>" + item.Url + "</td></tr>";  
  49.                 });  
  50.   
  51.                 // Appending HTML content  
  52.                 $('#blogs').append(htmlContent);  
  53.             },  
  54.             error: function (err) {  
  55.                 alert(err.statusText);  
  56.             }  
  57.         });  
  58.     }  
  59.   
  60.     // Searching a record 
  61.     function find() {  
  62.         var id = $('#blogId').val(); 

  63.         $.getJSON('http://localhost:1312/api/Blog/' + id + '?type=json')  
  64.             .done(function (data) {  
  65.                 var htmlContent = "<b>Blog</b>: " + data.Name + "<br/>" + "<b>Url</b>:" + data.Url;  
  66.                 $('#blog').html(htmlContent);  
  67.             })  
  68.             .fail(function (jqXHR, textStatus, err) {  
  69.                 $('#blog').text('Error: ' + err);  
  70.             });  
  71.     }  
  72. </script>  
Preceding code contains 3 AJAX requests. Firstly, AJAX request call to Web API and load all records to table (Figure 5). Secondly, AJAX request is for adding a record using HTTP POST method. Third, AJAX request is for searching a record and display it (Figure 6). 
 
 
Figure 5: Add New MVC project 
 
 
Figure 6: Add New MVC project
 

Send result in different formats like XML, JSON

 
After developing the WebAPI we need to host the service for client. There are different types of client with different type requirement. Means some client need result in XML format and same time some client need it JSON format. By default Web API returns result in XML format. So if our service need to support both the formats then we need to add code in WebApiConfig.cs file.
 
In order to accomplish above requirement, we will force the user to send us information what type format they need. And they will send the info by adding extra parameter type like the following url:
 
http://localhost:1312/api/Blog?type=xml
http://localhost:1312/api/Blog?type=json
 
If client need data in JSON format then type=json and same way if it is XML then type=xml,
 
Here is the complete code you need to add in WebApiConfig.cs file:
  1. public static void Register(HttpConfiguration config)  
  2. {  
  3.     config.Routes.MapHttpRoute(  
  4.         name: "DefaultExt",  
  5.         routeTemplate: "api/{controller}/{id}",  
  6.         defaults: new { id = RouteParameter.Optional }  
  7.     );  
  8.   
  9.     // To disable tracing in your application, please comment out or remove the following line of code  
  10.     // For more information, refer to: http://www.asp.net/web-api  
  11.     config.EnableSystemDiagnosticsTracing();  
  12.       
  13.     // Adding formatter for Json   
  14.     config.Formatters.JsonFormatter.MediaTypeMappings.Add(  
  15.         new QueryStringMapping("type""json"new MediaTypeHeaderValue("application/json")));  
  16.       
  17.     // Adding formatter for XML   
  18.     config.Formatters.XmlFormatter.MediaTypeMappings.Add(  
  19.         new QueryStringMapping("type""xml"new MediaTypeHeaderValue("application/xml")));  
  20. }  
Here client 1 needs data in XML then browse URL like http://localhost:1312/api/Blog?type=xml, See the following figure to see the output. 
 
Figure 7: Result in XML format
 
Here client 2 needs data in XML then browse URL like http://localhost:1312/api/Blog?type=json, See the following figure to see the output.
 
Figure 8: Result in JSON format
 

Conclusion

 
In this article we will discuss about Web API and its advantages. And also discuss how to send result in different format like XML, JSON based on query string parameter in URL.


Similar Articles