Introduction
In this article, I will demonstrate how to create a Web API using the ASP.NET MVC framework and consume it from a client application. Web API is new version of Microsoft’s service-oriented application built on top of MVC architecture. Web API is a great framework for exposing your data and service. It can be consumed by a broad range of clients, including browsers, mobiles, iPhone, and tablets. Web API supports conventional CRUD actions. It also supports MVC features such as routing, controllers, action results, filter, model binders, IOC container, and dependency injection; that makes it more simple and robust.
Creating a Web API in MVC and Consuming It from a Client Application
Let’s first create the ASP.NET MVC Web API project. The following steps are mentioned for creating a Web API and consuming it from the client application.
Step 1
Open Visual Studio 2017 and select “File” -> “New” -> “Project.”
In the Template Project Window, select Visual C# >ASP.NET Web Application and then select “Web API.” Change the name of the project to “MyWebAPI” and click the “OK” button (see Figures 1 and 2).
Figure 1: Creating a new Web API Project
Figure 2: Selecting a Web API Template
Step 2
We have to add a new model now. The Web API Model can be serialized automatically in JavaScript Object Notation (JSON) and Extensible Markup Language (XML) format. We can use the model to represent the data in our application.
To add a new model in the application, go to the Solution Explorer and right-click the “Model” folder. From the context menu, select “Add” and select the class. Name the class Employee.cs, as shown in Figure 3.
Figure 3: Adding a new Model in the Project
Step 3
Add the following code in the Employee class. I have created an employee and employee details classes.
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TestWebAPIProj.Models { public class Employee { public string EmployeeName { get; set; } public EmployeeDetails empdetails { get; set; } } public class EmployeeDetails { public string email { get; set; } public int age { get; set; } public double salary { get; set; } public string department { get; set; } public int totalexp { get; set; } } }
Step 4
Next, add a Controller. The Controller handles the HTTP requests. To add a new Controller, go to the Solution Explorer and right-click the “Controller” folder. Select “Add and Select Controller”. Change the name of the controller to “EmployeeController” (see Figure 4).
Figure 4: Adding a new Controller in the Project
From the Template, select “Web API 2 Controller – Empty”, as shown in Figure 5.
Figure 5: Selecting a Web API Controller Template
Step 5
My controller inherits the ApiController class and exposes two API methods. Now add the following code to the Employee Controller.
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using TestWebAPIProj.Models; using System.Web.Script.Serialization; namespace TestWebAPIProj.Controllers { public class EmployeeController : ApiController { public string GetEmpInfo(string JSONString) { var seriptSerialization = new System.Web.Script .Serialization.JavaScriptSerializer(); Employee employee = seriptSerialization .Deserialize<Employee>(JSONString); return "EmployeeName - " + employee.EmployeeName + "Employee Age- " + employee.empdetails.age + "Employee Dept - " + employee.empdetails.department + "Employee Email - " + employee.empdetails.email + "Employee Salary - " + employee.empdetails.salary + "Employee Experience - " + employee.empdetails.totalexp ; } public string SubmitEmpdata([FromBody]Employee emp) { return "EmployeeName - " + emp.EmployeeName + "Employee Age - " + emp.empdetails.age + "Employee Dept - " + emp.empdetails.department + "Employee Email - " + emp.empdetails.email + "Employee Salary - " + emp.empdetails.salary + "Employee Experience - " + emp.empdetails.totalexp; } } }
Step 6
Next, I have added the following route in the WebApiConfig.cs file present in App_Start folder.
public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter (OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); }
Step 7
We have to add client-side HTML code now and consume the Web API created in the previous step. In the Solution Explorer, expand the Home Folder and double-click Index.cshtml (see Figure 6).
Figure 6: Updating the Index.chtml view with HTML Code
Add the following code in the Index.cshtml page. I have called the GetEmpInfo () and SubmitEmpdata () API functions from JavaScript code. Now, execute the application to see the output.
<!DOCTYPE& <html> <head> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/ 1.11.1/jquery.min.js"></script> <title>ASP.NET Web API Sample</title> <link href="../../Content/Site.css" rel="stylesheet" /> <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script language="javascript" type="text/javascript"> var reqdata = { EmployeeName: "Robert Ben", empdetails: { email: 'robertben@hotmail.com', age: '50', salary: '10000', department: 'IT', totalexp: '10' } } var stringReqdata = JSON.stringify(reqdata); function GetEmpInfo() { var url = "http://localhost:58475/api/Employee/ GetEmpInfo?JSONString=" + stringReqdata; jQuery.ajax({ dataType: "json", url: url, async: false, context: document.body }).success(function (data) { alert(data); }); }; function SubmitEmpdata() { var url = "http://localhost:58475/api/Employee/ PostSubmitdata"; jQuery.ajax({ async: false, type: "POST", url: url, data: stringReqdata, dataType: "json", context: document.body, contentType: 'application/json; charset=utf-8' }).success(function (data) { alert(data); }) } </script> </head> <body> <a href="#" onclick="GetEmpInfo();"> Get Employee</a><br /> <a href="#" onclick="SubmitEmpdata();"> Post Employee</a> </body> </html>
Conclusion
Reading this article, you learned about Web APIs and how to consume them from a Web page. ASP.NET Web API is a framework that makes it easy to build HTTP services, and it’s an ideal platform for building RESTful applications on the .NET Framework.