ASP.NET

How to Create Rest API in C# ASP.NET Step by Step6 min read

In this article, I will show you how we can build restful APIs with ASP NET Web API.

Build Restful APIs with ASP.NET Web API in Visual Studio

Step 1. Open your visual studio and create new Project.




Step 2. Name your Project to your preference. In my case I name it as myRestAPI. Then press “OK”.

Step 3. Select Empty from your template window shown below and check Web API from the checkbox below the template option.

This is how your solution explorer looks for an Empty template project

Step 4. Now add Web API Controller class inside your Controllers folder. To add right click on your Controller folder, select Add then choose New Item.

Step 5. From the New Item window search for Web API Controller Class(v2) . Name your class controller then press Add.

The image below is the API Controller Default route:

Step 6. Before we proceed with this file (MyAPController), let’s create an additional class inside the Model folder. This will be used as a model to create our sample data later. To add, right-click on your Model folder, select Add, then choose New Item.

Step 7. Name your model. In my case, I name it as myModel.

Step 8. Open myModel class then declare properties below.

Solution Explorer Overview – Restful Web Services

  • WebApiConfig >> contains default url route for Api Controller
  • myAPIController >> Api controller that contains our method
  • myModel >> Contains model data properties.

Step 10. To access GetList(). Run your project and navigate to this URL localhost:7831/api/myAPI

Step 11. To access GetName(int id) >> localhost:7831/api/myAPI/GetName?id=1

Code Summary:

MyAPIController

myModel:

Now we have successfully build restful APIs with ASP NET Web API. Hopes this gives you an idea for your future projects. 

Source: https://www.freecodespot.com/blog/asp-net-web-api/

Leave a Comment