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 Class in the middle panel. Enter QuestionsController.cs for the name of the file and click Add:
- If the generated class doesn't inherit from ControllerBase, let's add this and remove the example action methods:
public class QuestionsController : ControllerBase
{
}
ControllerBase will give us access to more API-specific methods in our controller.
- If the generated class isn't decorated with the Route and ApiController attributes, let's add them:
[Route("api/[controller]")]
[ApiController]
public class QuestionsController : ControllerBase
{
}
The Route attribute defines the path that our controller will handle. In our case, the path will be api/questions because [controller] is substituted with the name of the controller minus the word controller.
The ApiController attribute includes behavior such as automatic model validation, which we'll take advantage of later in this chapter.