ASP.Net Web API

P.Madhanasekaran

Introduction

Asp Net Web API is a new Web service technology created by Microsoft with an aim to serve a broader range of clients including browsers, mobile devices etc. It is part of Asp Net platform and it provides resource- oriented HTTP REST web services. It should be distinguished from WCF, another web service technology from Microsoft. ASP Net Web API should also differentiated from Asp Net MVC, as they share the same programming model. Microsoft has taken some key classes and characteristics from the System.Web.Mvc namespace (Asp Net MVC) and duplicated them in the System.Web.Http namespace (Asp Net Web API). Look at the tables below which tries to compare these technologies:

WCF- Windows Communication Foundation

Asp Net Web API

Soap services; Rest service also

HTTP Rest services utilizing full features of HTTP 

Besides HTTP, Can use faster TCP, Named pipes also

Uses HTTP not only as a transport protocol but also  as an API

Can give Transaction, security etc.

Can give security.

Heavy as it complies with WS* protocol,  but powerful

Light weight but cannot match the power and flexibility of WCF

Target: enterprise users

Target: Wider clientele  including smart phone and notepad users

The web API is exactly the same as a normal MVC controller except that the base class is ApiController and has no support for view.

ASP Net MVC

ASP Net Web API

View layer also

No view layer

Sends browsers Content to display and also tells how to do it.

Different clients can use the services.  It sends data in JSON\xml and is data-centric. Clients can use the data for further computation or display using their own view technology

Regular  controller has actions that are view related e.g. index action is tied to index.cshtml

API controller has actions that provide data services and actions are named after HTTP verbs- more about this later.

Can also return JSONResult  for Ajax requests that update a part of a web page

JSON returned for further use-to support distributed architecture

Same application can have both ASP Net MVC and Web API.

Can be part of 1) ASP Net MVC app 2)  Asp Net Web Form App. 3) Or can provide a stand- alone web service.
But mostly used with  MVC .

Samples: In your “Visual Studio Express 2013 for Web” create a New Project. File -> New -> Project. In the wizard that appears expand -> Visual C#-> Web and choose ASP NET MVC 4 Web Application it may appear as in Figure-1.

If you click “OK” another Wizard will appear and choose “Web API”, as in Figure-2.

Figure-2

You can leave the view engine selected “Razor” and “Create a unit test project” check-box unchecked, as it is. The files and folders generated are both for the MVC and Web API. An introductory article entitled  ASP.NET MVC3 IN SHARP DEVELOP4.2 is available on DIQ site in July 2013 Archives .As pointed out there, it was inspired by Rails and follows “Conventions over Configuration”- For the conventions followed, please have look at the above article. If you have a look at the code generated by the IDE now, you can get a fair idea about Web API. Look inside the folders- Views, Controllers and App_Start . While the folder “Controllers” has controllers for both MVC and Web API, the folder “View”  has files only for MVC, as Web API has no view files.  App_Start has separate “route” files for MVC -RouteConfig.cs- and Web API- WebApiConfig.cs. There is a reason for two different route files for the two frameworks; the Web API feature is implemented as a stand-alone ASP.NET feature and it can be used outside of the MVC Framework also. Have a look the generated code for HomeController.cs and ValuesController.cs. The HomeController extends “Controller” base class. It has one action Index() which returns the control  to view /home/index.cshtml.  ValuesController of  Web API extends the base class ApiController. It has actions for processing all HTTP request methods -GET, POST,PUT and DELETE - and the action names correspond to the HTTP method names. Instead of customizing this generated class, we will use this as a template for coding a “custom” controller later on.

Models : Right Click on Models folder and Add a New -> Class. Name the file “Employee.cs”. Replace the in the empty class generated, with the following:

Employee.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Practical.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
}

You can see that some automatic properties have been added and the compiler will generate getters and setters for them.

Add a controller

Right click on Controllers folder and choose Add à Controller. In the Wizard that appears you can give the name “EmployeesController” and choose in Template “Empty API Controller” as shown in Figure-3 below:

When you click “Add” only a skeleton class- without methods- will be generated   as we chose only an Empty controller.                              

The code for the EmployeesController.cs  may be filled up as under. The names of actions can be the HTTP method names as in ValuesController.cs,  but for the purpose of learning we have slightly modified them:

EmployeesController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using FirstWebAPI.Models;
namespace FirstWebAPI.Controllers
{
    public class EmployeesController : ApiController
    {
public Employee Get(int id)
{
return new Employee()
{
Id = id,
Name = "Ramasamy",
Department = "Enforcement"
};
}

        public IEnumerable<Employee> GetAllEmployees()
{
return new Employee[]
{
new Employee()
{
Id = 123,
Name = "Ramasamy",
Department = "Development"
},
new Employee()
{
Id = 124,
Name = "Prasanna",
Department = "Support"
}
};
}                
[HttpPost]
        public void Add(Employee employee)  //----------4)
        {
            int maxId = list.Max(e => e.Id);
            employee.Id = maxId + 1;
            list.Add(employee);
        }
           [HttpPut]
        public void Update(int id, Employee employee)  //----5)
        {
            int index = list.ToList().FindIndex(e => e.Id == id);
            list[index] = employee;
        }
        // DELETE api/employees/12345
        public void Delete(int id)
        {
            Employee employee = Get(id);
            list.Remove(employee);
        }
    }
}

  1. As this is a small sample, we have put the data in the controller itself; otherwise we have to use a repository, or get it from a database table.
  2. As mentioned above, the name of an action should be that of a HTTP method or at-least contain it .The API controller maps the requests to actions on the basis of HTTP methods used to make the request. We will see more about this when we see the routing files.
  3. Both the names of methods GetAllEmployees() and Get(id) contain GET. When the controller has to choose between two methods for a request, it looks at the arguments to the methods and whether the routing variable has any value for those arguments. Here a parameter- less GET  request will go to GetAllEmployees() and if a GET request carries a value for Id, then it goes to Get(id).
  4. & 5) Add() and Update() convey better what they are doing than the names Post and Put, but  they do not contain the  name of HTTP methods. So API Controller needs some help to map the requests for these actions. So attributes are affixed to them. The attributes show which type of HTTP requests should be forwarded to them.

Build and Start the application:

If you build and then start the application, the development server in VS will start and the default Browser will open and appear as under:

If you add api/Employees( we will see Why in the next paragraph)  to the navigation bar the request goes to the action GetAllEmployees() in EmployeesController and you will see Figure-5.If your default browser is Internet Explorer  you will get Figure-6.When you click Open, you will get Figure-7. IE shows data as JSON , while other Browsers show XML. This difference is due to the difference in wording the header of a request by various Browsers. But if we want the Web API to send only “JSON” and not XML to any Browser, we can configure it- we will see how to do it in the next article.

 

 

Routing Files

If you expand App_Start you can see among other things two routing files 1) RouteConfig.cs  meant for  MVC framework  2) WebApiConfig.cs meant for Web API framework. Have a look at them. You can find that they use different classes from different name spaces to define the routes. But the main difference is in the components of “url”  . For MVC “url”  has to contain the following: 1) controller’s name( without the suffix Controller)  2)name of action . In the url of  Web API,  the string “/api/” has to precede the Controllers name (without the suffix –Controller) and action name should not be specified as the framework can infer it from the HTTP method used.

Support for JQuery

If have a look in the project folder you can see under “Scripts” a number of JQuery related files there. Asp Net MVC4 has a built-in feature called unobtrusive Ajax and unobtrusive client-side validation which makes use of JQuery underneath.MVC4 also allows you to use JQuery directly. The Web API has no view layer but mostly the client to the API is coded in JavaScript. MVC4 can act as a Client for Web API. Here we can replace the entire code in Views/Home/index.cshtml with the following JQuery/JavaScript code to access the Web API.

@section scripts{
<script type="text/javascript">
$(function () {   //--------1)
$('#search').click(function () {  //  ----4)
$('#employees').empty();
$.getJSON("/api/employees", function (data) {  //---------5)
$.each(data, function (i, employee) {      //-----6)
var content = employee.Id + ' ' + employee.Name;
content = content + ' ' + employee.Department;
$('#employees').append($('<li/>', { text: content }));  //-----7)
});
});
});
});
</script>
}
<div>
<div>
<h1>
Employees Listing
</h1>
<input id="search" type="button" value="Get" />  //------2)
</div>
<div>
<ul id="employees" />  //----------3)
</div>
</div>

  1. This is a short-hand notation for $(document).ready() function. JQuery is a tool for manipulation of DOM elements. The Code segment given within this function will execute when the document is ready (i.e., when the page content is loaded and DOM is created). To ensure that the manipulation starts only after that, the entire code is put within $(document).ready ().
  2. There are two <div> in the page. The first <div> contains a button -id “search”, on the click of which an anonymous function is triggered.
  3. The second <div> contains an unordered list to which the data obtained from the web service is appended.
  4. See note 2) above.
  5. The “url”  of the web service and a callback function are passed to the function getJSON() in JQuery.
  6. Within the above callback function , each() in  JQuery-  similar to “forEach” in C#- is used to fetch and append the data to the unordered list “employees”.
  7. As mentioned above, jQuery is meant for manipulating DOM elements. Here the data fetched is appended to the element “employees”.

If you debug after saving the file- no recompilation is necessary- you may see Figure-8.When you click GET you may see Figure-9.

Conclusion:

Since we have earlier used Asp Net MVC, it won’t take long to start using Web API, as they follow the same programming model. The model class is the same old POCO. The controller classes are similar except that a different base class is used and a few conventions are followed in naming actions. As the Web API does not have any view layer we have used the view file of MVC framework used in the same project to code with jQuery/JavaScript and make use of the Web API.  But our aim should be to access the services from a different origin- as we did earlier in our JEE and Angular sample. If you can recall, there, we enabled “CORS” (Cross Origin Resource Sharing). CORS is a World Wide Web Consortium (W3C) specification (commonly considered part of HTML5) that lets JavaScript overcome the same-origin policy security restriction imposed by browsers. The same-origin policy means that our JavaScript can only make AJAX calls back to the same origin of the containing Web page (where “origin” is defined as the combination of host name, protocol and port number). For example, JavaScript on a Web page from http://foo.com can’t make AJAX calls to http://bar.com (or to http://www.foo.com, https://foo.com or even http://foo.com:888).

CORS relaxes this restriction by letting servers indicate which origins are allowed to call them. CORS is enforced by browsers but must be implemented on the server, and ASP.NET Web API 2 has CORS support. With Web API 2, we can configure policy to allow JavaScript clients from a different origin to access our APIs. We will see more about this in the next article.
This article is written by P. Madanasekaran. For more information you can send an email to sekaran.madhan@gmail.com








}