Introduction:
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.
- Controller Name (in url controller name is must. It is first parameter of url).
- Action Name (in url action name is must. It is second parameter of url).
- Id (individual)(it is manadatory)
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:
- namespace MyFirstWebAPI.Controllers
- {
- public class ValuesController : ApiController
- {
-
- public IEnumerable<Customer> Get()
- {
- return new List<Customer>()
- {
- new Customer (){CustomerId=1, CustomerName="Amit"},
- new Customer(){CustomerId=2,CustomerName="Sumit"}
- };
- }
-
- public Customer Get(int id)
- {
- if (id == 1)
- {
- return new Customer() { CustomerId = 1, CustomerName = "Amit" };
-
- }
- else if (id == 2)
- {
- return new Customer() { CustomerId = 2, CustomerName = "Sumit" };
-
- }
- return null;
- }
- }
- }
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:
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: