ASP.NET MVC 5: Web API With implementation


Today, we'll learn how to use the Web API in the ASP.NET MVC 5 application. 
Create ASP.NET  MVC 5.0 Web API Application 

Open new project

A lot of features of WebAPI are similar to ASP.NET MVC,
Here's one more scenario.

Point 1:

In ASP.NET MVC Controller class is inherited from MVC controller.

Point 2:

In Web API values Controller it is inherit from API Controller.

Now here, I will discuss other points.

In any MVC url contains the 3 values given values.

  1. Controller Name (in url controller name is must. It is first parameter of url).
  2. Action Name (in url action name is must. It is second parameter of url).
  3. Id (individual)(it is manadatory)

 After that,

Here in WebApi there is no need for action method. It only takes api name and cotroller. But in MVC controller action method (Result)  must be required. Now Next Step:

Add a Class: 

After that complete code here: 
  1. namespace MyFirstWebAPI.Controllers  
  2. {  
  3.     public class ValuesController : ApiController  
  4.     {  
  5.         // GET api/values  
  6.         public IEnumerable<Customer> Get()  
  7.         {  
  8.             return new List<Customer>()  
  9.            {  
  10.            new Customer (){CustomerId=1, CustomerName="Amit"},  
  11.            new Customer(){CustomerId=2,CustomerName="Sumit"}  
  12.            };  
  13.         }  
  14.         // GET api/values/ 10  
  15.         public Customer Get(int id)  
  16.         {  
  17.             if (id == 1)  
  18.             {  
  19.                 return new Customer() { CustomerId = 1, CustomerName = "Amit" };  
  21.             }  
  22.             else if (id == 2)  
  23.             {  
  24.                 return new Customer() { CustomerId = 2, CustomerName = "Sumit" };  
  26.             }  
  27.             return null;  
  28.         }  
  29.     }  
  30. }   

Execute it now showing

When I typed url : localhost:1031/api/values then IEnumerable<Customer> Get() method. In this url I have not passed a particular customer id due to this reason it show all records of customer list.

And result will be shown like. 

localhost:1031/api/values/1  in this url we specify the customer id then it will show the record of given specific id.
For test it  we can use Fiddler.

Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. Fiddler allows you to inspect traffic, set breakpoints, and "fiddle" with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language.
 It also return output in XML or JSON format. 
Read more articles on ASP.NET:

Similar Articles