The Web API was introduced in MVC 4. It is a framework to create RESTfull services to support a large number of clients like browsers and mobile/tablet devices. Microsoft also has REST WCF. But WCF does require many more configuration settings than the Web API and we can host the Web API in our own applications.

WCF or ASP.NET Web API

Create a new web application with the template "Web API". Delete all the default controllers, models and views.

Web API

The Web API supports MVC routing. If you open "WebApiConfig.cs" then you can see that. Since we will not use any atuthentication and authorizatoion I have changed the Register method in this file as:

  1. public static void Register(HttpConfiguration config)
  2. {
  3. config.MapHttpAttributeRoutes();
  4. config.Routes.MapHttpRoute(
  5. name: "DefaultApi",
  6. routeTemplate: "api/{controller}/{action}/{id}",
  7. defaults: new { id = RouteParameter.Optional }
  8. );
  9. }
And Startup.cs as:
  1. public partial class Startup
  2. {
  3. public void Configuration(IAppBuilder app)
  4. {
  5. }
  6. }
To get data for our API, I have created a dummy DB as follows. Of course, in a real application, you would query a database or use some other external data source.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Collections;
  6. namespace HelloWebAPI.Models
  7. {
  8. public class EmployeeModel
  9. {
  10. public int EmployeeId { get; set; }
  11. public string EmployeeName { get; set; }
  12. public string EmployeeDepartment { get; set; }
  13. public decimal Salary { get; set; }
  14. public int ManagerId { get; set; }
  15. }
  16. public class DunmmyEmployeeDB
  17. {
  18. public static List<EmployeeModel> EmployeeDB = null;
  19. static DunmmyEmployeeDB()
  20. {
  21. EmployeeDB = new List<EmployeeModel>();
  22. EmployeeDB.Add(new EmployeeModel { EmployeeId = 11, EmployeeName = "Abhinandan", EmployeeDepartment = "CTS", ManagerId = 0, Salary = 83232 });
  23. EmployeeDB.Add(new EmployeeModel { EmployeeId = 1, EmployeeName = "Amit", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 34343 });
  24. EmployeeDB.Add(new EmployeeModel { EmployeeId = 2, EmployeeName = "Sushil", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 6565 });
  25. EmployeeDB.Add(new EmployeeModel { EmployeeId = 3, EmployeeName = "Gauri", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 24578 });
  26. EmployeeDB.Add(new EmployeeModel { EmployeeId = 4, EmployeeName = "Rahul", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 34543 });
  27. EmployeeDB.Add(new EmployeeModel { EmployeeId = 5, EmployeeName = "Rajib", EmployeeDepartment = "MST", ManagerId = 15, Salary = 45454 });
  28. EmployeeDB.Add(new EmployeeModel { EmployeeId = 6, EmployeeName = "Savan", EmployeeDepartment = "MST", ManagerId = 15, Salary = 2323 });
  29. EmployeeDB.Add(new EmployeeModel { EmployeeId = 7, EmployeeName = "Nafisul", EmployeeDepartment = "MST", ManagerId = 15, Salary = 34322 });
  30. EmployeeDB.Add(new EmployeeModel { EmployeeId = 8, EmployeeName = "Hemant", EmployeeDepartment = "MST", ManagerId = 15, Salary = 4321 });
  31. EmployeeDB.Add(new EmployeeModel { EmployeeId = 9, EmployeeName = "Sandeep", EmployeeDepartment = "MST", ManagerId = 15, Salary = 3456 });
  32. EmployeeDB.Add(new EmployeeModel { EmployeeId = 10, EmployeeName = "Ganesh", EmployeeDepartment = "MST", ManagerId = 15, Salary = 8765 });
  33. EmployeeDB.Add(new EmployeeModel { EmployeeId = 12, EmployeeName = "Devesh", EmployeeDepartment = "Testing", ManagerId = 0, Salary = 84344 });
  34. EmployeeDB.Add(new EmployeeModel { EmployeeId = 13, EmployeeName = "Yogesh", EmployeeDepartment = "Testing", ManagerId = 12, Salary = 4343 });
  35. EmployeeDB.Add(new EmployeeModel { EmployeeId = 14, EmployeeName = "Bhavik", EmployeeDepartment = "Testing", ManagerId = 12, Salary = 3547 });
  36. EmployeeDB.Add(new EmployeeModel { EmployeeId = 15, EmployeeName = "Manjul", EmployeeDepartment = "MST", ManagerId = 0, Salary = 73547 });
  37. }
  38. }
  39. }
Now add an empty WebAPI Controller as we do in a normal MVC application as in the following:

WebAPI Controller

We can see here that this new controller is inherited form ApiController instead of Controller.
  1. namespace HelloWebAPI.Controllers
  2. {
  3. public class EmployeeController : ApiController
  4. {
  5. }
  6. }
First we would add a method to get all the Employee data. For this I have added a method to my controller as in the following:
  1. public IEnumerable GetAllEmployees()
  2. {
  3. return DunmmyEmployeeDB.EmployeeDB;
  4. }
  5. Change the Application_start as
  6. protected void Application_Start()
  7. {
  8. GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
  9. GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
  10. AreaRegistration.RegisterAllAreas();
  11. GlobalConfiguration.Configure(WebApiConfig.Register);
  12. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  13. RouteConfig.RegisterRoutes(RouteTable.Routes);
  14. BundleConfig.RegisterBundles(BundleTable.Bundles);
  15. }
Since this supports the MVC Routing we can access this service at:

http://localhost:[port]/api/Employee/GetAllEmployees.

Now run the application. It will open our index view of the home controller. Now open the rest client from Firebox and call the API with the get method as shown. We will get the JSON for the entire employee in our DB.

entire employee in our D

We can also get the information of one single user. For this we need to pass a parameter to our service. So our new service would look such as:
  1. public IHttpActionResult GetEmployeeData(int id)
  2. {
  3. var Employee = DunmmyEmployeeDB.EmployeeDB.FirstOrDefault((p) => p.EmployeeId == id);
  4. if (Employee == null)
  5. {
  6. return NotFound();
  7. }
  8. return Ok(Employee);
  9. }
And our service URL would be:

http://localhost:[port]/api/Employee/GetEmployeeData?id=10

or

http://localhost:[port]/api/Employee/GetEmployeeData/10

Employee

Since we know REST has mainly the following four methods:

By default the API works with HttpGet. We can also use the other HTTP methods by decorating our action methods with [HttpPost] or [HttpPut] or [HttpDelete].

Now decorate GetEmployeeJsonData with [HttpPost] and try to run the preceding URL. You will get "The requested resource does not support http method 'GET'".

requested resource

GET

As I motioned earlier, the Web API uses MVC routing so Web API2 can also use the attribute routing that is a new feature introduced in MVC 5. To test this we can decorate the action as in the following:

  1. [Route("api/Employees")]
  2. [HttpGet]
  3. public IEnumerable GetAllEmployees()
  4. {
  5. return DunmmyEmployeeDB.EmployeeDB;
  6. }
DunmmyEmployeeDB

For more on Attribute Routing please refer to this link.

Passing Complex Data to Service

We have learned how to pass simple data as an argument to a service. We can also pass complex data as JSON to the service. Create one new service method that takes an object of EmployeeModel as an argument.
  1. public HttpResponseMessage RecieveEmployeeJsonData(EmployeeModel obj)
  2. {
  3. var responce = Request.CreateResponse(HttpStatusCode.OK, "Recieved");
  4. return responce;
  5. }
Passing Complex Data to Service

responce

Please note that we need to add contentType: 'application/json; charset=utf-8' in the headers.

We can call the post service with jQuery as in the following:
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title></title>
  5. <script src="http://code.jquery.com/jquery-latest.js"></script>
  6. </head>
  7. <body>
  8. <button id="TestService" onclick="CallAPI()">Test Service</button>
  9. <script type="text/javascript">
  10. function CallAPI() {
  11. var Employee = {
  12. EmployeeId: 12,
  13. EmployeeName: 'Devesh',
  14. EmployeeDepartment: 'Testing',
  15. Salary: 4344,
  16. ManagerId: 10
  17. };
  18. var str = JSON.stringify(Employee);
  19. $.ajax({
  20. url: 'http://localhost:14925/api/Employee/RecieveEmployeeJsonData',
  21. cache: false,
  22. type: 'POST',
  23. contentType: 'application/json; charset=utf-8',
  24. data: str,
  25. dataType: "json",
  26. success: function (data) {
  27. alert('succeed');
  28. }
  29. }).fail(
  30. function (xhr, textStatus, err) {
  31. alert(err);
  32. }
  33. );
  34. }
  35. </script>
  36. </body>
  37. </html>
code