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
- If you want to create resource-based services and need to take full advantage of HTTP like cache control for browsers, transfer various kinds of content types like documents, images and HTML pages then ASP.NET Web API should be selected.
- If you have heterogeneous clients for the same service and need to call the service using various protocols, like netTCPBinding, netNamedPipeBinding and wsHttpBinding then WCF is the obvious choice.
- If you have special requirements like CallBackContract, one-way communication or queuing then WCF should be selected.
Create a new web application with the template "Web API". Delete all the default controllers, models and views.
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:
- public static void Register(HttpConfiguration config)
- {
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{action}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
And Startup.cs as:
- public partial class Startup
- {
- public void Configuration(IAppBuilder app)
- {
-
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Collections;
- namespace HelloWebAPI.Models
- {
- public class EmployeeModel
- {
- public int EmployeeId { get; set; }
- public string EmployeeName { get; set; }
- public string EmployeeDepartment { get; set; }
- public decimal Salary { get; set; }
- public int ManagerId { get; set; }
- }
-
- public class DunmmyEmployeeDB
- {
- public static List<EmployeeModel> EmployeeDB = null;
- static DunmmyEmployeeDB()
- {
- EmployeeDB = new List<EmployeeModel>();
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 11, EmployeeName = "Abhinandan", EmployeeDepartment = "CTS", ManagerId = 0, Salary = 83232 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 1, EmployeeName = "Amit", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 34343 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 2, EmployeeName = "Sushil", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 6565 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 3, EmployeeName = "Gauri", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 24578 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 4, EmployeeName = "Rahul", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 34543 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 5, EmployeeName = "Rajib", EmployeeDepartment = "MST", ManagerId = 15, Salary = 45454 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 6, EmployeeName = "Savan", EmployeeDepartment = "MST", ManagerId = 15, Salary = 2323 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 7, EmployeeName = "Nafisul", EmployeeDepartment = "MST", ManagerId = 15, Salary = 34322 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 8, EmployeeName = "Hemant", EmployeeDepartment = "MST", ManagerId = 15, Salary = 4321 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 9, EmployeeName = "Sandeep", EmployeeDepartment = "MST", ManagerId = 15, Salary = 3456 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 10, EmployeeName = "Ganesh", EmployeeDepartment = "MST", ManagerId = 15, Salary = 8765 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 12, EmployeeName = "Devesh", EmployeeDepartment = "Testing", ManagerId = 0, Salary = 84344 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 13, EmployeeName = "Yogesh", EmployeeDepartment = "Testing", ManagerId = 12, Salary = 4343 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 14, EmployeeName = "Bhavik", EmployeeDepartment = "Testing", ManagerId = 12, Salary = 3547 });
- EmployeeDB.Add(new EmployeeModel { EmployeeId = 15, EmployeeName = "Manjul", EmployeeDepartment = "MST", ManagerId = 0, Salary = 73547 });
-
- }
- }
- }
Now add an empty WebAPI Controller as we do in a normal MVC application as in the following:
We can see here that this new controller is inherited form ApiController instead of Controller.
- namespace HelloWebAPI.Controllers
- {
- public class EmployeeController : ApiController
- {
- }
- }
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:
- public IEnumerable GetAllEmployees()
- {
- return DunmmyEmployeeDB.EmployeeDB;
- }
- Change the Application_start as
- protected void Application_Start()
- {
- GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
- GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
- AreaRegistration.RegisterAllAreas();
- GlobalConfiguration.Configure(WebApiConfig.Register);
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
- }
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.
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:
- public IHttpActionResult GetEmployeeData(int id)
- {
- var Employee = DunmmyEmployeeDB.EmployeeDB.FirstOrDefault((p) => p.EmployeeId == id);
- if (Employee == null)
- {
- return NotFound();
- }
- return Ok(Employee);
- }
And our service URL would be:
http://localhost:[port]/api/Employee/GetEmployeeData?id=10
orhttp://localhost:[port]/api/Employee/GetEmployeeData/10
Since we know REST has mainly the following four methods:
- GET: This should be used to retrieve the required state of a resource.
- PUT: This should be used to update the required state of a resource.
- POST: This should be used to create a new resource.
- DELETE: This should be used to delete the required state of a resource.
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'".
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:
- [Route("api/Employees")]
- [HttpGet]
- public IEnumerable GetAllEmployees()
- {
- return DunmmyEmployeeDB.EmployeeDB;
- }
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.
- public HttpResponseMessage RecieveEmployeeJsonData(EmployeeModel obj)
- {
-
- var responce = Request.CreateResponse(HttpStatusCode.OK, "Recieved");
- return 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:
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title></title>
- <script src="http://code.jquery.com/jquery-latest.js"></script>
- </head>
- <body>
- <button id="TestService" onclick="CallAPI()">Test Service</button>
- <script type="text/javascript">
-
- function CallAPI() {
- var Employee = {
- EmployeeId: 12,
- EmployeeName: 'Devesh',
- EmployeeDepartment: 'Testing',
- Salary: 4344,
- ManagerId: 10
-
-
-
- };
-
- var str = JSON.stringify(Employee);
- $.ajax({
- url: 'http://localhost:14925/api/Employee/RecieveEmployeeJsonData',
- cache: false,
- type: 'POST',
- contentType: 'application/json; charset=utf-8',
- data: str,
- dataType: "json",
- success: function (data) {
- alert('succeed');
- }
- }).fail(
- function (xhr, textStatus, err) {
- alert(err);
- }
-
- );
- }
- </script>
-
- </body>
- </html>