Introduction
In this article we will discuss about Web API and its return types. Here is the agenda of this article:
- What is Web API.
- What are advantages of Web API(against WCF).
- Demo Web API with CRUD operation.
- 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.
- public class Blog
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string Url { get; set; }
- }
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:
- public class BlogController : ApiController
- {
- public static List<Blog> blogList = new List<Blog>()
- {
- new Blog { Id = 1, Name="C-SharpCorner", Url="http://www.c-sharpcorner.com/"},
- new Blog { Id = 2, Name="CodeProject", Url="http://www.codeproject.com"},
- new Blog { Id = 3, Name="StackOverflow", Url="http://stackoverflow.com/"},
- };
-
-
- public List<Blog> Get()
- {
- return blogList;
- }
-
-
- public Blog Get(int id)
- {
- Blog blogObject = (from blog in blogList
- where blog.Id == id
- select blog).SingleOrDefault();
- return blogObject;
- }
-
-
- public List<Blog> Post(Blog blogObj)
- {
- blogList.Add(blogObj);
-
- return blogList;
- }
-
-
- public void Put(Blog blogObj)
- {
- Blog blogOrignalObject = (from blog in blogList
- where blog.Id == blogObj.Id
- select blog).SingleOrDefault();
-
- blogOrignalObject.Name = blogObj.Name;
- blogOrignalObject.Url = blogObj.Url;
- }
-
-
- public void Delete(int id)
- {
- blogList.RemoveAll(temp => temp.Id == id);
- }
- }
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.
- <div>
- <h2>All Blogs</h2>
- <table border="1" cellpadding="0" cellspacing="0" id="blogs">
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Url</th>
- </tr>
- </table>
- </div>
- <div>
- <h2>Search by ID</h2>
- <input type="text" id="blogId" size="5" />
- <input type="button" value="SearchBlog" onclick="find();" />
- <p id="blog" />
-
- <h1>Add Blog</h1>
- Id:
- <input type="text" id="Id" /><br />
- Name:
- <input type="text" id="Name" /><br />
- Url:
- <input type="text" id="Url" /><br />
- <input type="button" value="AddBlog" onclick="add();" />
- </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:
- <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
- <script>
- $(document).ready(function () {
-
-
- $.ajax({
- url: 'http://localhost:1312/api/Blog?type=json',
- type: "GET",
- data: {},
- dataType: "json",
- success: function (result) {
-
- var htmlContent = "";
-
- $.each(result, function (key, item) {
- htmlContent = htmlContent + "<tr><td>" + item.Id + "</td><td>" + item.Name + "</td><td>" + item.Url + "</td></tr>";
- });
-
-
- $('#blogs').append(htmlContent);
- },
- error: function (err) {
- alert(err.statusText);
- }
- });
- });
-
- // Adding Blog record
- function add() {
- var Id = $('#Id').val();
- var Name = $('#Name').val();
- var Url = $('#Url').val();
- var blogData = { "Id": Id, "Name": Name, "Url": Url };
-
- $.ajax({
- url: 'http://localhost:1312/api/Blog?type=json',
- type: "POST",
- contentType: "application/json",
- data: JSON.stringify(blogData),
- dataType: "json",
- success: function (result) {
-
- var htmlContent = "";
-
- $("#blogs > tbody > tr").remove();
-
- $.each(result, function (key, item) {
- htmlContent = htmlContent + "<tr><td>" + item.Id + "</td><td>" + item.Name + "</td><td>" + item.Url + "</td></tr>";
- });
-
-
- $('#blogs').append(htmlContent);
- },
- error: function (err) {
- alert(err.statusText);
- }
- });
- }
-
- // Searching a record
- function find() {
- var id = $('#blogId').val();
- $.getJSON('http://localhost:1312/api/Blog/' + id + '?type=json')
- .done(function (data) {
- var htmlContent = "<b>Blog</b>: " + data.Name + "<br/>" + "<b>Url</b>:" + data.Url;
- $('#blog').html(htmlContent);
- })
- .fail(function (jqXHR, textStatus, err) {
- $('#blog').text('Error: ' + err);
- });
- }
- </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:
- public static void Register(HttpConfiguration config)
- {
- config.Routes.MapHttpRoute(
- name: "DefaultExt",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
-
-
-
- config.EnableSystemDiagnosticsTracing();
-
-
- config.Formatters.JsonFormatter.MediaTypeMappings.Add(
- new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
-
-
- config.Formatters.XmlFormatter.MediaTypeMappings.Add(
- new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
- }
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.