Creating an API Controller
Explore the process of creating API controllers in ASP.NET Core to handle HTTP requests for REST API endpoints. Understand how to inject data repositories using dependency injection to keep your controllers decoupled and maintainable.
We'll cover the following...
An API controller is a class that handles HTTP requests for an endpoint in a REST API and sends responses back to the caller.
In this section, we are going to create an API controller to handle requests to an api/questions endpoint. The controller will call into the data repository we created in the previous section. We’ll also create an instance of the data repository in the API controller using dependency injection.
Creating an API controller for questions
Let’s create a controller for the api/questions endpoint. If we don’t have our backend project open in Visual Studio, let’s do so and carry out the following steps:
In “Solution Explorer”, right-click on the “Controllers” folder, choose “Add”, and then “Class…”.
In the left-hand panel, find and select ASP.NET Core and then “API Controller - Empty” in the middle panel. Enter
QuestionsController.csfor the name of the file and click “Add”: