In this article we are going to create a simple Web API, that basically exposes an in-memory List<Student> over HTTP, for a client application to play with the list members.
Although this article would have relatively limited applicability to a practical web API implementation, it is a foundation toward understanding how to use the ASP.NET Web API framework to build your web API.
Run Visual Studio and create a new ASP.NET Web Application. Give the project a name of StudentAPI. Select the ‘Web API’ template which will automatically select MVC and Web API Checkboxes. For now you can leave Authentication method use for API by default it is “No Authentication”.
Right-click on the Controllers folder in the Solution Explorer. Select Add => Controller and select MVC API 2 Controller -Empty. Other API option like controller with actions , using entity frame work etc, are scaffolding templates that write starter code for you. Then give controller name to StudentController.
It create the class StudentController that inherits from ApiController. It serves as a base class for all the resources that we decide to expose via the API.
Now we need to add a model class with name of Students, in the model folder.
Now we will create a list of Students in controller.
Then we will add the Action Methods to Get, Post, Put, and Delete Students. after adding methods, our controller is
Now build and run the project, it show the home page with URL of http://localhost:xxxxx/. In the fiddler request composer type http://localhost:<port>/api/Students Replace <port> with the actual port your application runs on, then we would get result in json:
We can also get the details of a specific student by performing an HTTP GET on http://localhost:xxxxx/api/students/2. In this case, we get the JSON:
I hope that you will have better understanding of process for building your own Web API. I would like to hear valuable feedback or question from you. It encourage me to write more quality article.
Happy Reading 🙂