Getting Started with JSON APIs in ASP.NET

Learn about the basic components that are needed to make an API controller class.

To enable JSON Web APIs, you have to create a new controller class in your controller’s folder. It is preferred to place these controllers inside a folder called Api, which sits inside your controller’s folder. This controller class requires the attribute [ApiController] for the framework to figure out that this class will be used for JSON API purposes.


As covered before, ASP.NET extracts the route from the controller class’s name. To modify this behavior, especially in the case of APIs, we can use the following line of code:


This is unlike your controller classes that return a view and map routes with respect to the names of their action methods. For APIs, multiple action methods route to the same URL endpoint. They are only differentiated with the help of the HTTP attribute assigned to them. This will be covered in more detail in the next few lessons.

Controller inheritance

Your views controller inherits the Controller class, whereas your APIs controller class will inherit the ControllerBase class.

public class UsersController : ControllerBase

Keep in mind that the Controller class also inherits from ControllerBase but adds additional functionality to support views.

Injecting database context

In order to access your database to perform Web API’s equivalent of CRUD operations, inject database context via the controller’s constructor and access it throughout the class with the _context variable.

Get hands-on with 1200+ tech skills courses.