ASP.NET Web API 2 In MVC 5 Using C# With Example


This article gives an explanation about how to create and access the Web API 2 in the ASP.NET MVC 5 application using C# and bootstrap with examples. Here I'll also show you how to create the step by step Web API 2 in ASP.Net MVC 5 Using C# and bootstrap with a simple example. In this tutorial, you will use ASP.NET Web API 2 to create a web API and that returns a list of employees.
Many developers/programmers who work with ASP.Net, MVC, Java, PHP, Python will have at least heard talk about the Web API. Even if any developers/programmers know on a basic level what Web API does, they are not always certain when to use Web API and how to write the code to use Web API, etc. So, in this article, I am going to explain how to create web API in MVC applications and how to use Web API in a web application with an example.
  • Create ASP.NET MVC Web API Application using Bootstrap.
  • Get a list of All Employees.
  • Search Employee Based on Employee ID and Display on Screen.


So, let's start with a simple example of the employee where we will retrieve all the information of the employee using WEB API.
Step 1
Open Your Visual Studio 2013 or higher versions.
Step 2
Go to the File menu and Create New Project same as shown below.
Step 3
Now you can see the following popup window on your screen. You have to follow some steps as shown in the screen below.
Step 4
Now, when you click on the OK button you can see another popup window will appear on your screen same as shown below, where you have to select WEB API and click OK.
Step 5
Finally, your WEB API project has been created and your project structure looks as shown below.
Step 6
Now, if you can see, two default created controllers are available where you have to open your controller file "ValuesController.cs" and need to do the following modification in your controller.
Here, I will change my Controller Name ValueController to EmployeeController which is derived from ApiController.
  1. public class EmployeeController: ApiController  
Now, I will create a simple class and define some basic properties of employees such as ID, Name, Designation, Salary and etc.
  1. public class Employee  
  2. {  
  3.     public int EmpId { getset; }  
  4.     public string EmployeeName { getset; }  
  5.     public string Designation { getset; }  
  6.     public decimal Salary { getset; }  
  7. }  
Then I will define a simple array and store some sample data of employees on it.
  1. Employee[] Employees = new Employee[]{  
  2.     new Employee {EmpId=1,EmployeeName="Nikunj Satasiya", Designation="Software Engineer", Salary=78000},  
  3.     new Employee {EmpId=2,EmployeeName="Hiren Dobariya", Designation="Software Engineer", Salary=72000},  
  4.     new Employee {EmpId=3,EmployeeName="Vivek Ghadiya", Designation="Software Engineer", Salary=75000},  
  5.     new Employee {EmpId=4,EmployeeName="Pratik Pansuriya", Designation="Software Engineer", Salary=55000},  
  6.     new Employee {EmpId=5,EmployeeName="Nikunj Ladani", Designation="Software Engineer", Salary=42000},  
  7.     new Employee {EmpId=6,EmployeeName="Sarah Demola", Designation="Software Engineer", Salary=90000}  
  8. };  
Now, I will write a method which returns all the details of Employee for every employee.
  1. public IEnumerable<Employee> GetAllEmployees()  
  2. {  
  3.     return Employees;  
  4. }  
Then I will write a second method which returns details of the single employee based on employee id.
  1. public IHttpActionResult Get(int Id)  
  2. {  
  3.     var Employee = Employees.FirstOrDefault((e) => e.EmpId == Id);  
  4.     if (Employee == null)  
  5.     {  
  6.         return NotFound();  
  7.     }  
  8.     return Ok(Employee);  
  9. }  
Step 7
Now, it's time to add a simple HTML form in our application and for that, you have to follow some steps described on the screen below.
Step 8
Now, you have to write the following code in the HTML file.
HTML Markup
  1. <!DOCTYPE html>    
  2. <html xmlns="">    
  3. <head>    
  4.     <title>Codingvila Web API</title>    
  5.     <script src=""></script>    
  6.     <link rel="stylesheet" type="text/css" href="Content/bootstrap.css"/>    
  7.     <link rel="stylesheet" type="text/css" href="Content/bootstrap.min.css"/>    
  8. </head>    
  9. <body class="container">    
  10.     <div>    
  11.         <h2>All Employees</h2>    
  12.         <ul id="Employees" />    
  13.     </div>    
  14.     <div>    
  15.         <h2>Search by Employee ID</h2>    
  16.         <input type="text" style=" width:50%" class="form-control" id="EmpId" size="5" />    
  17.         <br />    
  18.         <input type="button"  class="btn btn-primary" value="Search" onclick="FindEmployee();" />    
  19.         <br />    
  20.         <br />    
  21.         <p id="Employee" style=" width:50%" />    
  22.     </div>    
  25.     <script>    
  26.         var uri = 'api/employee';    
  28.         $(document).ready(function () {    
  29.             // Send an AJAX request    
  30.             $.getJSON(uri)    
  31.                 .done(function (data) {    
  32.                     // On success, 'data' contains a list of Employee.    
  33.                     $.each(data, function (key, Data) {    
  34.                         // Add a list Data for the Employee.    
  35.                         $('<div>', { text: formatData(Data) }).appendTo($('#Employees'));    
  36.                         });    
  37.                 });    
  38.         });    
  40.         function formatData(Data) {    
  41.             return 'Name :-' + Data.EmployeeName + ', Designation :- ' + Data.Designation + ', Salary :- ' + Data.Salary;    
  42.         }    
  44.         function FindEmployee() {    
  45.             var id = $('#EmpId').val();    
  46.             $.getJSON(uri + '/' + id)    
  47.                 .done(function (data) {    
  48.                     $('#Employee').text(formatData(data));    
  49.                     $('#Employee').removeClass('alert alert-danger');    
  50.                     $('#Employee').addClass('alert alert-success');    
  51.                 })    
  52.                 .fail(function (jqXHR, textStatus, err) {    
  53.                     $('#Employee').text('Error: ' + err);    
  54.                     $('#Employee').addClass('alert alert-danger');    
  55.                     $('#Employee').removeClass('alert alert-success');    
  56.                 });    
  57.         }    
  58.     </script>    
  59. </body>    
  60. </html>    
Step 9
Now you have to run your application and for that, you can press F5 and your web page looks as shown below.
Search Employee By Employee ID
Step 10
To View the HTTP Request and Response you have to press F12, and then click on the Network tab and then press start capturing red icon and now go back to the web page and reload the web page or press F5 to reload the web page. You can see the HTTP Request and Response as shown below.


This article gives an explanation about how to create and access the Web API 2 in the ASP.NET MVC 5 application using C#.
To download the sample source code please visit the given reference link and download it from there.
Reference Link

Codingzee is an educational knowledge sharing website, developed for helps students and beginners.